当字符串包含一个精确的子字符串例如2次时,我需要一个正则表达式。所以
asdgsadg hello asdadsg hello dasadg
将是真的
asdgsadg hello asdadsg hello dasadg hello
将是假的
子字符串为hello
不幸的是,我无法/hello/g
并计算长度...
谢谢!
答案 0 :(得分:1)
答案 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