barruntlek
barruntlek

Reputation: 67

Regex selecting numbers

I am trying to capture the numbers in the text below with regex. But it seems to fail on the last text, which only has one digit inside a parenthesis. I can't figure out why since my knowledge with Regex is limited.

Any suggestions?

Regex

[\s(](\d[\d,\.\s]+)

Text

This banana costs 0,5 usd from previous (50)
The toothbrush is worth 0,8 usd (1,5)
This orange costs 1 usd from previous 10 usd
My car is now worth 1 000 (1 800)
This apple now costs 1 usd (1)

Results

0,5     50
0,8     1,5
1       10
1 000   1 800
1

Link to regex101: https://regex101.com/r/uy9OOc/1

Upvotes: 0

Views: 56

Answers (1)

The fourth bird
The fourth bird

Reputation: 163247

Your pattern matches at least 2 characters, being a digit and 1 or more times one of \d , . \s

You can match either a space or ( and then capture a single digit followed by optionally repeating the chars in the character class.

[\s(](\d[\d,.\s]*)

See a regex demo.

If you don't want trailing spaces, dots or comma's:

[\s(](\d+(?:[\d,.\s]*\d)?)\b

Explanation

  • [\s(] Match either a whitespace char or (
  • ( Capture group 1
    • \d+ Match 1+ digits
    • (?:[\d,.\s]*\d)? Optionally match one of the chars in the character class followed by a digit
  • ) Close group 1
  • \b A word boundary to prevent a partial word match

Regex demo

Upvotes: 2

Related Questions