matching numbers with regex with specific requirement

Viewed 40

I would like to match following bold marked numbers in a Text with numbers and text.

some text 12.444 12,444 12'444 123.122 12.1234 12345 1234 12.12 12.1234567 12.242Text 12.242 Text Text12.242 Text12.242Text

Numbers with a dotlike seperators should only have 3 following digits. If number has more digits it should be ignored. The Number should be matched as a whole. 12.34567 should not match to 34567.

The Numbers should match as a whole so I could later match "from 12.123 to 56.789" with 2 groups group1 : 12.123 group2 : 56.786

I started with following regex which did not match the needs:

[?<!\d][0-9]{1,2}[,|\.][0-9]{3}[?!\d]
2 Answers

You can use

(?<!\S)(?:[0-9]{1,2}[,.'][0-9]{3}|[0-9]{3,})(?!\S)

See the regex demo. NOTE: If the fractional part in the 1-2 digit numbers is optional wrap it with an optional group, (?:[,.'][0-9]{3})?:

(?<!\S)(?:[0-9]{1,2}(?:[,.'][0-9]{3})?|[0-9]{3,})(?!\S)

Details:

  • (?<!\S) - a left-hand whitespace boundary
  • (?: - start of a non-capturing group:
    • [0-9]{1,2} - one or two digits
    • [,.'] - comma, dot or '
    • [0-9]{3} - three digits
  • | - or
    • [0-9]{3,} - three or more digits
  • ) - end of the group
  • (?!\S) - a right-hand whitespace boundary

Apart from the square brackets that should be parenthesis, asserting not a digit on the left or right will still be true in case of a character like T

To match all bold values you could use:

(?<!\S)[0-9]+(?:[,.'][0-9]{3})?(?!\S)
  • (?<!\S) Assert non a non whitespace char on the left
  • [0-9]+ Match 1 or more digits
  • (?:[,.'][0-9]{3})? Match an optional decimal part with 3 digits
  • (?!\S) Assert non a non whitespace char on the right

Regex demo

The pattern will match either numbers with 3 decimals or 1 or more digits.

Related