shAkur
shAkur

Reputation: 1002

Regex to match second number in a group of numbers starting with predefined characters

Is it possible to match the number in between other numbers from a predefined set of characters looking like:

TOTAL 600,00 571,43 28,57

What I want: 571,43

What I'm trying: TOTAL[ ]*([^\s]+)[ ]*

What I get: 600

Any help is much appreciated! Thanks.

Upvotes: 2

Views: 732

Answers (3)

Mike
Mike

Reputation: 11

total = "600,00 571,43 28,57"
numbers_needed = ["571", "43", "18"]
result = []

numbers_needed.each do |number|
  result << number if p total.match(Regexp.new(number))
end

p result

You can create a new regular expression in ruby using Regexp::new, and return the proper variable for comparison. Here, I just created an array of all the needed variables(numbers_needed) and iterated through through them, utilizing the each method, and passing the block parameter number to Regexp::new. If there is a match, I append the result to the array result. It is not the most efficient, but that's where my starting place landed me. I included a number that should not be found to verify that it was working correctly. You could use match? to return boolean values here too.

the result outputs ["571", "43"]

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163362

You can match the first number and capture the second number in a group:

\bTOTAL \d+(?:,\d+)? (\d+(?:,\d+)?)\b

Explanation

  • \bTOTAL Match TOTAL and a space ([ ]* matches optional spaces, \s can also match a newline)
  • \d+(?:,\d+)? match 1+ digits with an optional decimal part and a space
  • (\d+(?:,\d+)?) Capture group 1, match 1+ digits with an optional decimal part
  • \b A word boundary to prevent a partial match

Regex demo

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626896

You can capture the second number after TOTAL in the following way:

TOTAL(?:\s*(\d+(?:,\d+)?)){2}

See the regex demo. Detail:

  • TOTAL - a word
  • (?:\s*(\d+(?:,\d+)?)){2} - two occurrences of
  • \s* - zero or more whitespaces
  • (\d+(?:,\d+)?) - Group 1: one or more digits followed with an optional occurrence of a comma and one or more digits

Note that the (?:\s*(\d+(?:,\d+)?)){2} is a repeated non-capturing group, and the Group 1 value will contain the last number matched with the capturing group (since the {2} quantifier is used, it will be the second matched number).

Upvotes: 3

Related Questions