Regex matches 1-3 digits after a known string in Ruby

I need to match the numbers in the following lines. Perhaps they can be part of longer lines with other numbers in them, so I specifically want to match the number (number) that occurs immediately after the space following the text "Error code" :

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

It is also possible:

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

I am using someString.match(regEx)[0] but I cannot use the regular expression correctly.

+4
source share
4 answers
 /(?:Error Code )[0-9]+/ 

This uses a non-capture group (not available in all regular expression implementations). He will say that String will have this phrase better, but I do not want this phrase to be part of my correspondence, but only the numbers that follow.

If you only need 1 to three digits:

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

With Ruby, you have to face very small restrictions in your regular expression. Other than conditional expressions, there are not many Ruby regular expressions.

+17
source

I would use the following regular expression:

 /Error\sCode\s\d{1,3}/ 

Or, with named groups:

 /Error\sCode\s(?<error_code>\d{1,3})/ 

The latter will record the error code, number, under the named group. Note that \s matches spaces, but this is not necessary if the x flag is not specified. You can access the following entries:

 str = "Error Code 0\nError Code 45\nError Code 190" error_codes = str.lines.map{|l|l.match(regex)[:error_code]} #=> ["0", "45", "190"] 
+4
source

Given the line "Error code 190", this will return "190" rather than "Error code", as shown in the example with another example of a regular expression.

 (?<=Error Code.*)[0-9] 
+4
source

You can use this regex: Only numbers read from 1 to 3:

 regexp = "^\\d{1,3}$" 
0
source

All Articles