Search code examples
javascriptregexcurrency

regex search digit or digit and space to length of search term in js. In this case, 3-5 characters, if there are spaces


me find the values "ddd", "dsdd", "ddsd" from the list below: "150 EUR 15 000 EUR 150 150 EUR 1 500 EUR".

I tried:

/(\d{3})|(\d+\s\d{1,2})/gm

The result of the test: (The bold value should not be matched)

  • 150
  • 15 00
  • 150
  • 150
  • 1 50

Solution

  • The second part of your alternation \d+\s\d{1,2} matches only a single whitspace char only once, and \d+ matches 1 or more digits and \d{1,2} match one or 2 digits.

    To match 3 digits, with either a whitespace char between the first and second, or second and third digit, or match 3 digits only:

    \b\d(?:\s?\d|\d\s)\d
    

    The pattern matches:

    • \b A word boundary to prevent a partial word match
    • \d Match a digit
    • (?: Non capture group for the alternatives
      • \s?\d match an optional whitspace char followed by a digit
      • | Or
      • \d\s Match a digit followed by a whitspace char
    • ) Close the group
    • \d Match a digit

    See a regex demo