Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number position in string

Tags:

mysql

position

Below is what I have in table myTable

+++++++++++++++
+ id + myWord +
+++++++++++++++
+  1 + AB123  +
+  2 + A413D  +
+  3 + X5231  +
+  4 + ABE921 +
+++++++++++++++

When I execute

SELECT id, Locate('1',myWord) as myPos
FROM myTable;

I get position of 1.

+++++++++++++++
+ id + myPos  +
+++++++++++++++
+  1 + 3      +
+  2 + 3      +
+  3 + 5      +
+  4 + 6      +
+++++++++++++++

What I want to achieve is finding first position of integer so that I will have below output.

+++++++++++++++++++++++
+ id + myWord + myPos +
+++++++++++++++++++++++
+  1 + AB123  +  3    +
+  2 + A413D  +  2    +
+  3 + X5231  +  2    +
+  4 + ABE921 +  4    +
+++++++++++++++++++++++

Any Idea how I can achieve this?

like image 939
Fahim Parkar Avatar asked Jun 21 '12 09:06

Fahim Parkar


People also ask

How do you find the position of a number in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the position of a word in a string?

Method #1 : Using re. findall() + index() This is one of the way in which we can find the location where word exists. In this we look for substring pattern using findall() and its position using index().

How do you find the position of a number in a string in Python?

Method 1: Get the position of a character in Python using rfind() Python String rfind() method returns the highest index of the substring if found in the given string. If not found then it returns -1.

How do you get the first position of a string?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found.


1 Answers

With help of xdazz answer, I did some changes and got answer finally...

SELECT 
  myWord, 
  LEAST (
    if (Locate('0',myWord) >0,Locate('0',myWord),999),
    if (Locate('1',myWord) >0,Locate('1',myWord),999),
    if (Locate('2',myWord) >0,Locate('2',myWord),999),
    if (Locate('3',myWord) >0,Locate('3',myWord),999),
    if (Locate('4',myWord) >0,Locate('4',myWord),999),
    if (Locate('5',myWord) >0,Locate('5',myWord),999),
    if (Locate('6',myWord) >0,Locate('6',myWord),999),
    if (Locate('7',myWord) >0,Locate('7',myWord),999),
    if (Locate('8',myWord) >0,Locate('8',myWord),999),
    if (Locate('9',myWord) >0,Locate('9',myWord),999)
  ) as myPos
FROM myTable;

Demo

like image 132
Fahim Parkar Avatar answered Sep 24 '22 12:09

Fahim Parkar