shAkur
shAkur

Reputation: 1002

Regex to match the last number on different rows

Is it possible to match the last number from a different row, looking like:

Total fara TVA TVA Total 171,11 RON 32,51 RON 203,62 RON

What I want: 203,62

What I'm trying regexr.com/64to5 : Total(?:\s*(\d+(?:,\d+)?)){1}

What I get: 171,11

Any help is much appreciated! Thanks.

Upvotes: 1

Views: 48

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133730

With your shown samples, please try following regex.

\bTotal.*(?<=\s)(\d+,\d+)\s+

Online demo for above regex

Explanation: Adding detailed explanation for above.

\bTotal.*  ##Using word boundary along with string Total followed by .* greedy match here.
(?<=\s)    ##using positive look behind to make sure spaces are present before next mentioned regex.
(\d+,\d+)  ##Creating 1st capturing group to match 1 or more occurrences of digits followed by comma and followed by 1 or more digits.
\s+        ##matching 1 or more occurrences of spaces here.

OR as per fourth brid's nice suggestion: without positive lookbehind try following:

\bTotal.*\s(\d+,\d+)\s+

Upvotes: 3

The fourth bird
The fourth bird

Reputation: 163577

You might use a capture group:

\bTotal\b.*(?<![\d,])(\d+(?:,\d+)?)\b
  • \bTotal\b Match Total between word boundaries to prevent a partial match
  • .* Match any char except a newline
  • (?<![\d,]) Negative lookahead, assert not a digit or , to the left
  • ( Capture group 1
    • \d+(?:,\d+)? Match 1+ digit with an optional decimal part
  • ) Close capture group
  • \b A word boundary

Regex demo

If you don't want to cross matching Total again before the number:

 \bTotal\b(?:(?!\bTotal\b).)*(?<![\d,])(\d+(?:,\d+)?)\b

Regex demo

Upvotes: 3

Related Questions