John Smith John Smith - 1 year ago 137
Ruby Question

Match String with Number Placeholder

I would like to match the following strings: With String match:

"The account 340394034 is finalized"

"The account 9394834 is finalized"

"The account 12392039483 is finalized"

"The account 3493849384 is finalized"

"The account 32984938434983 is finalized"

Which regex do I have to use to match this strings with number placeholders in it? Thanks

"The account {number_placeholder} is finalized"

Answer Source

If you just want to use the match method to determine whether a given string matches the pattern in your examples, you can do this:

example = "The account 32984938434983 is finalized"

if example.match(/The account \d+ is finalized/)
  puts "it matched"
  puts "it didn't match"

The match method returns a MatchData object (basically the part of the string that matched the regex, which in this case is the whole thing). Using it on a non-matching string will return nil, this means you can use the result of the match method for if-statements.

If you want to extract the number in the string, only if the string matches the pattern, you could do this:

example = "The account 32984938434983 is finalized"
match_result = example.match(/The account (\d+) is finalized/)

number = if match_result
           number = nil # or 0 / some other default value

The brackets in the regex form a "capture group". The captures method on the result gives an array of all the capture group matches. The first method gets the first (and in this case only) element from that array, and the to_i method converts the string into an integer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download