Reputation: 6447
I'm trying to match a string like " 23.0 32.0". Here's my regex:
hrs_pnt_regex = /\s{2,}-?\d{1,2}\.\d(\s+|$)/
Code:
x = " 23.0 32.0"
x.to_enum(:scan, hrs_pnt_regex).map { Regexp.last_match }
Result:
MatchData " 23.0 " 1:" "
What I notice is that the \s+ doesn't seem to work in the parens at the end. If I change it to "\s\s", it matches both numbers like so. Otherwise I get only the first one.
<MatchData " 23.0 " 1:" ">, <MatchData " 32.0" 1:"">
Does + not work with a | after it?
Upvotes: 0
Views: 79
Reputation: 810
The best thing to do here is to use an online Regex Matcher. My favorite is RegExr.
Best I can tell from your description is you want to match numbers simular to xx.y
, in which case
hrs_pnt_regex = /\d{2,}\.\d{1,2}/
will match both sets, 23.0
and 32.0
Upvotes: 0
Reputation: 211670
The problem is that the (\s+|$)
part is consuming the spaces that subsequent matches need to identify the starting part. You're basically sabotaging your next round by gobbling up all those spaces and leaving the pointer at the 3
position at the start of 32.0
. So long as they're considered part of the first match, they won't be available for the second.
A quick fix is:
x.scan(/\s{2,}(-?\d{1,2}\.\d)/)
# => [["23.0"], ["32.0"]]
Upvotes: 1