Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match Number of 1-3 Digits After a Known String in Ruby

I need to match the numbers in the following strings. It is possible they may be part of longer strings with other numbers in them, so I specifically want to match the number(s) occuring directly after the space which follows the text 'Error Code':

Error Code 0  # Match = 0
Error Code 45 # Match = 45
Error Code 190 # Match = 190

Also possible:

Some Words 12 Error Code 67 Some Words 77 # Match = 67

I'm using someString.match(regEx)[0] but I can't get the regex right.

like image 467
Undistraction Avatar asked Nov 28 '22 09:11

Undistraction


2 Answers

/(?:Error Code )[0-9]+/

This uses a non-capturing group (not available in all regex implementations.) It will say, hey the String better have this phrase, but I don't want this phrase to be part of my match, just the numbers that follow.

If you only want between 1 and three digits matched:

/(?:Error Code )[0-9]{1,3}/

With Ruby you should run into very few limitations with your regex. Aside from conditionals, there isn't very much Ruby's regex cannot do.

like image 78
BlackVegetable Avatar answered Dec 05 '22 15:12

BlackVegetable


Given the string "Error Code 190", this will return "190" and not "Error Code" like the other regex example provided here.

(?<=Error Code.*)[0-9]
like image 33
Brian Salta Avatar answered Dec 05 '22 16:12

Brian Salta