'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.
Solution 1:[1]
/(?: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.
Solution 2:[2]
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]
Solution 3:[3]
I'd use the following regex:
/Error\sCode\s\d{1,3}/
Or, with named groups:
/Error\sCode\s(?<error_code>\d{1,3})/
The last one will capture the error code, the number, under a named group. Note that \s matchs whitespaces but it's unnecessary unless the x flag is specified. You can access match captures like this:
str = "Error Code 0\nError Code 45\nError Code 190"
error_codes = str.lines.map{|l|l.match(regex)[:error_code]}
#=> ["0", "45", "190"]
Solution 4:[4]
You can use this regexp: Only digits, count from 1 to 3:
regexp = "^\\d{1,3}$"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | the Tin Man |
| Solution 2 | Brian Salta |
| Solution 3 | |
| Solution 4 | zond |
