正则表达式在一组数字内零或更多空格

时间:2016-11-28 02:33:57

标签: regex

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

([\d\s*]{1,3})

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

无论如何,谢谢。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

((?:\d\s*){1,3})

Demo

说明:

((?:\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

你也可以这样做:

 ^(\d\s*\d?\s*\d?\s*)
  ^                 ^     capture group
    ^                     one digit
      ^                   zero or more spaces
         ^                optional digit
            ^             zero or more spaces
               ^  ^       etcetera..... 

Demo

答案 1 :(得分:0)

我想,

(\d{1,3}\s*)应该能得到你想要的东西。它定义了一个由1-3位数组成的组,以及出现在下一组数字之前的任何空格。如果您不想在组中包含空格,可以使用(\d{1,3})\s*

相关问题