4

I am trying to get the integer value between two specific strings but I am stacked a little bit.

Example full string:

"The real ABC4_ string is probably company secret."

I need to get the "4" between "ABC" and "_". First I've came up with following script:

select substring_index(substring_index('The real ABC4_ string is probably company secret.', 'ABC', -1),'_', 1);

It gives me 4, perfect! But the problem is if ABC occurs more than one time in the string it fails. I can't simply increase the counter also since I don't know how many times it will be in the future. I have to get first occurrence of that regex: ABC[DIGIT]_

I've seen REGEXP_SUBSTR function but since we use older version of MySQL than 8.0 I can't use it also.

Any suggestions?

Thanks!

2
  • Perhaps you need to do it in app code. Commented Oct 15, 2019 at 0:56
  • @RickJames Yes I had to move this to code, it's probably the most efficient (actually the only one I came up with) solution. Commented Oct 15, 2019 at 7:25

2 Answers 2

2

Without using Regex, here is an approach using LOCATE(), and other string functions:

SET @input_string = 'The real ABC4_ string is probably company secret.';

SELECT TRIM(LEADING 'ABC' 
              FROM SUBSTRING_INDEX(
                     SUBSTR(@input_string FROM 
                       LOCATE('ABC', @input_string)
                           )
                     ,'_', 1
                     )
           ) AS number_extracted;

| number_extracted |
| ---------------- |
| 4                |

View on DB Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

For a string like this it fails: SET @input_string = 'The real ABC_ string is probably company secretABC4_.';
Except duplicate cases like mine (in the previous comment) it works perfectly, I am approving the answer but please keep in mind this scenario dear future readers.
1

Another way of (ab)using the LOCATE() function:

select    substr('The real ABC4_ string is probably company secret.',
   locate('ABC', 'The real ABC4_ string is probably company secret.') + 3,
      locate('_','The real ABC4_ string is probably company secret.') - 
   locate('ABC', 'The real ABC4_ string is probably company secret.') - 3) AS num;

1 Comment

For a string like this it fails: SET @input_string = 'The real ABC_ string is probably company secretABC4_.'; As I understand from the query, you are looking for the first ABC string than the first _ string and get between those two. I need to look for all the scenarios like 1- ABC exists, 2- _ exists, 3- integer between these two exists 4- If there is more than one satisfying below rules, take the first one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.