Juned Ansari
Juned Ansari

Reputation: 5283

Regular Expression to get substring from main string

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

Upvotes: 0

Views: 136

Answers (1)

Sweeper
Sweeper

Reputation: 270980

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)?

Upvotes: 2

Related Questions