0

I am trying to get sub-string based on some pattern. trying to fetch first number which should not be in first character of main string.

Strings:

BRUSPAZ 8MG
BRUSPAZ MG
BRUSPAZ 10 MG
BRUSPAZ10 MG
AVAS 40
AVAS 40 TEST 2TABS
MICROCEF CV 200 TABS 
1CROCIN DS 240 MG / 5 ML SUSPENSION

My Regular Expression : /(\d+)( )?(MG)?/

enter image description here

Required Output:

enter image description here

4
  • How is the 10 in BRUSPAZ10 not in the first word? Commented Dec 21, 2017 at 9:39
  • @Sweeper sorry not in first word, it should not be first character Commented Dec 21, 2017 at 9:41
  • can you show us the expected outputs instead of an image, i can't check the image (company rules :() Commented Dec 21, 2017 at 9:43
  • Do you want a pure regex solution? Commented Dec 21, 2017 at 9:43

1 Answer 1

2

This is the regex:

(?<!^)(\d+)(\s*MG)?
  • I changed the ( )? to \s* so as to account for other kinds of whitespace and more than one of them.
  • I added a (?<!^). This is a negative lookbehind, looking for ^ - the start of the string. Basically it says that "there should not be the start of the string before the digits".
  • If you run this regex line by line, and turning of the global modifier, you will not match the 5 in the last line.

If you want to match decimals as well, use this:

(?<!^)(\d+\.\d+)(\s*MG)?
Sign up to request clarification or add additional context in comments.

3 Comments

Try using a negative look ahead in your regular expression. Try looking that up. If you still can't figure out, ask a new question. @JunedAnsari
it does not extract float number eg. ALVACE 2.5MG
@JunedAnsari You should have said that in the question! Anyway, see the edit.

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.