正则表达式:精确包含n次字符串

时间:2017-04-28 09:05:04

标签: javascript regex

当字符串包含一个精确的子字符串例如2次时,我需要一个正则表达式。所以

asdgsadg hello asdadsg hello dasadg将是真的

asdgsadg hello asdadsg hello dasadg hello将是假的

子字符串为hello

不幸的是,我无法/hello/g并计算长度...

谢谢!

3 个答案:

答案 0 :(得分:1)

正则表达式是:

/^(?!(.*hello){N+1})(.*hello){N}.*$/

'N+1' = 3'N' = 2,如果您想准确地允许2 hello

See demo

答案 1 :(得分:0)

这就是工作:

/^(?:(?!\bhello\b).)*(?:\bhello\b(?:(?!\bhello\b).)*){2}$/



var test = [
    'asdadsg hello dasadg',
    'asdgsadg hello asdadsg hello dasadg',
    'asdgsadg hello asdadsg hello dasadg hello',
];
console.log(test.map(function (a) {
  return a+' :'+/^(?:(?!\bhello\b).)*(?:\bhello\b(?:(?!\bhello\b).)*){2}$/.test(a);
}));




<强>解释

/
  ^
  (?:                   : non capture group
    (?!\bhello\b).      : asserts there is not hello, followed by a character
  )*                    : group repeated 0 or more times
  (?:                   : non capture group
    \bhello\b           : hello
    (?:                 : non capture group
      (?!\bhello\b).    : asserts there is not hello, followed by a character
    )*                  : group repeated 0 or more times
  ){2}                  : group repeated twice
  $
/

答案 2 :(得分:0)

这是我迄今为止找到的最简单的解决方案 <svg> <defs> <pattern id="wood" patternUnits="userSpaceOnUse" width="240" height="300" > <image xlink:href="http://hd.wallpaperswide.com/thumbs/girl_beach_background-t2.jpg" width="400" height="400" /> </pattern> </defs> <text y="2em">Nice Beach</text><text y="3em">Isnt't It</text> </svg> Run code snippet