Reputation: 67
I'm trying to match different variations of distance presentation which works pretty well for bigger values but fails on single digits
^(?:(?<distanceMeter>\d+[,|.]?\d+?) ?\/? ?(?<distanceFemaleMeter>\d+?[,|.]?\d+?)?) ?-m ?(?<text>[\w\s]+)
matches
But it fails to match
I thought d+ always matches 1 or more digits, but its not working.
Upvotes: 1
Views: 54
Reputation: 163477
In the pattern that you tried you use \d+?
which matches at least 1 digits, and making it non greedy matches the least amount, but there still has to be at least a single digit.
Note that using (?:\d+)?
is the same as \d*
, and using [\w\s]+
at the end can also match only whitespace chars (that can also match only newlines) You can use a space instead, as in the rest of the pattern you also match spaces.
Your examples should all match the digits at the start, and are followed by an optional /
and digits part and then the -m
part should be present followed by "text"
For that format, you can make the whole part with /
and the digits optional.
^(?<distanceMeter>\d+(?:[,.]\d+)?)(?: ?\/ ?(?<distanceFemaleMeter>\d+(?:[,.]\d+)?))? ?-m ?(?<text>\w+(?: \w+)*)
^
Start of string(?<distanceMeter>\d+(?:[,.]\d+)?)
Group distanceMeter, match 1+ digits with an optional decimal part(?:
Non capture group
?\/ ?
Match /
between optional spaces(?<distanceFemaleMeter>\d+(?:[,.]\d+)?)
Group distanceFemaleMeter, match 1+ digits with an optional decimal part)?
Close the non capture group and make it optional ?-m ?
Match -m
between optional spaces(?<text>\w+(?: \w+)*)
Group text, match 1+ word chars and optionally repeat a space and 1+ word charsSee a regex demo.
Upvotes: 1
Reputation: 67
After posting I actually figured out that creating a new group can handle this, so instead of \d+? using (?:\d+)? works
^(?:(?<distanceMeter>\d+[,|.]?(?:\d+)?) ?\/? ?(?<distanceFemaleMeter>\d+?[,|.]?(?:\d+)?)?) ?-m ?(?<text>[\w\s]+)
Upvotes: 0