正则表达式一组数字中的零个或多个空格

jd9*_*d94 5 regex

假设我有一个一到三个数字的序列,它们之间可以有任意数量的空格,并假设这些数字在我可以反向引用的组内。我该怎么做呢?这是我到目前为止所拥有的

([\d\s*]{1,3})
Run Code Online (Sandbox Code Playgroud)

我只是有点困惑我如何拥有一个最多匹配三位数的模式,然后在它们之间有零个或多个空格,并将它们保留在一个组中。

不管怎样,谢谢。

daw*_*awg 5

你可以做:

((?:\d\s*){1,3})
Run Code Online (Sandbox Code Playgroud)

演示


解释:

((?:\d\s*)){1,3}
  ^      ^        define a non capturing group
     ^            a single digit
       ^          a space zero or more times
^         ^       capture that group (digit and following space pattern)
           ^      1 to 3 times
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

 ^(\d\s*\d?\s*\d?\s*)
  ^                 ^     capture group
    ^                     one digit
      ^                   zero or more spaces
         ^                optional digit
            ^             zero or more spaces
               ^  ^       etcetera..... 
Run Code Online (Sandbox Code Playgroud)

演示