Link to home
Start Free TrialLog in
Avatar of tmajor99
tmajor99

asked on

Regular Expression to detect number preceding word

I need help with a regular expression that will only pick up the number preceding a certain word "GAL".  I need to pick up only the number up to the first space or /.

Data                                                                   Expected Results:
-----------------------------------                                ---------------------------
55 GAL DRUMS T PLUS 2                                55
Test 10 GAL DRUMS T PLUS 2                       10
200 500 1 GAL                                                  1
GAL 100 DRUM                                                [nothing]
100 KW/500 GAL Drum                                  500
XX GAL                                                              [nothing]
X1 GAL                                                              1
Avatar of Bill Prew
Bill Prew

You could try:

[ \/]([0-9]+)

And grab off the first submatch.

https://regex101.com/r/WalH4R/1

~bp
ASKER CERTIFIED SOLUTION
Avatar of Jon Norman
Jon Norman
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How about this?

\d+(?=[\s\/]GAL)
Whoops, I read the GAL need, and then forgot it in my example.  Looks like you've got some other feedback now, let us know how that gores...

~bp
@Jon Norman

I think positive look ahead would be better approach instead of having a non capturing group?
Positive look ahead will return the desired output in the full match.
In case a newline character shouldn't be matched, a literal space character may be better than \s. Otherwise a positive lookahead seems sensible.
\d+(?= GAL)
@ Terry

I used \s instead of a single literal space for the scenario if there are multiple white spaces  before the string GAL.
\s still only matches one space character, or a tab or newline. Did you want to put a + after it?
Oh yes, that makes sense.
@tmajor99,

Are you all set with this now, or do you need more help?  If all set, could you please close it out now.  If you need help with the question close process take a look at:



»bp