Mark Summers
Mark Summers

Reputation: 23

I need a regex to capture just the number from a string

I do not have access to the code, this is via an interface that only allows me to edit the regex that parses user responses. I need to extract the weight after users text, where they text things like:

wt 172.5 172.5 lbs 180 wt. 173.22 172,5

I need to capture the weight as a float field, but I want to restrict it to at most 1 decimal place. I tried using /(?<val>[\d+((\.|,)\d\d?)?]/ but it is only saving the first digit "1" in the field

Upvotes: 2

Views: 90

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110665

Sometimes what seems most simple is not. I suggest using this regex:

r = /(?<=\A|\s)\d+(?:[.,]\d)?(?=\d|\s|\z)/

We can alternatively define the regex using extended or free-spacing mode (by adding the modifier x after the final /), which allows us to include documentation:

r = /
    (?<=\A|\s)  # match beginning of string or space in a positive lookbehind
    \d+         # match one or more digits
    (?:[.,]\d)? # optionally (? after non-capture group) match a . or , then a digit
    (?=\d|\s|\z) # match a digit, space or the end of the string in a positive lookahead
    /x

"wt 172.5"[r]      #=> "172.5" 
"172.5 lbs"[r]     #=> "172.5" 
"180"[r]           #=> "180" 
"wt. 173.22"[r]    #=> "173.2" 
"172,5"[r]         #=> "172,5" 
"A1 143.66"[r]     #=> "143.6" 
"A1 1.3.4 43.6"[r] #=> "43.6" 

Upvotes: 2

vks
vks

Reputation: 67968

\d+(?:[,.]\d{1,2})?

Guess you wanted this .[] is character class,not what you think.Your character class captures just one out of all characters you have defined.

See demo.

https://regex101.com/r/eB8xU8/12

Upvotes: 0

Related Questions