正确的正则表达式语法以限制匹配组的总长度

时间:2018-08-24 17:23:48

标签: javascript regex

我想制作一个正则表达式来匹配可以包含多个单词的名称。 但同时我想将总长度限制为20。

我使用了select * into #t3 from (select col1, col2, . . . from #t1 union all select col1, col2, . . from #t2 ) t; --- alias missing

我正在获取语法,但是它没有检查字长约束。为什么?

注意:我正在用Javascript编写代码。

3 个答案:

答案 0 :(得分:1)

var test = [
    "abc123 def456 ghi789",
    "123456789012345678901",
    "123456",
];
console.log(test.map(function (a) {
  return a+' :'+/^(?=.{1,20}$)\w+(?: \w+)*$/.test(a);
}));

说明:

^                   : beginning of line
    (?=.{1,20}$)    : positive lookahead, make sure we have no more than 20 characters
    \w+             : 1 or more word character
    (?: \w+)*       : a space followed by 1 or more word char, may appear 0 or more times
$

答案 1 :(得分:0)

请参见Limit number of character of capturing group

这仍然会匹配,但限制为20。(进行了一些编辑,但我认为是...)

let rx = /(?=\b(\w+(\s\w+)*)\b).{1,20}/

let m = rx.exec('one two three four')
console.log(m[0])
console.log(m[0].length)

m = rx.exec('one two three four five six seven eight')
console.log(m[0])
console.log(m[0].length)

m = rx.exec('wwwww wwwww wwwww wwwww wwwww')
console.log(m[0])
console.log(m[0].length)

答案 2 :(得分:0)

轻微修改-尝试执行此操作({1,20}在外部here上:

In[1]:avergeIncreace(df,'A')
Out[1]:75
In[2]:avergeIncreace(df,'B')
Out[2]:0
In[3]:avergeIncreace(df,'C')
Out[3]:10