7

Regex is the number of 1-3 digits after a known string in Ruby

 2 years ago
source link: https://www.codesd.com/item/regex-is-the-number-of-1-3-digits-after-a-known-string-in-ruby.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Regex is the number of 1-3 digits after a known string in Ruby

advertisements

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.


/(?: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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK