Search code examples
regexregex-group

Regex matching different numbers in meter presentation


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

  • 2000/ 1,500-m row and
  • 2000-m row

But it fails to match

  • 10/ 5-m row
  • 9-m row

I thought d+ always matches 1 or more digits, but its not working.


Solution

  • 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 chars

    See a regex demo.