[英]Match a single occurrence of a string in a sentence using regEx
If a sentence says如果一句话说
"Hello Hello" “你好你好”
the test should return false, but if its something like测试应该返回false,但如果它像
"Hello Jhon" “你好约翰”
it returns true.它返回真。
I thought this is all i had to do /(hello){1}/
我以为这就是我要做的全部/(hello){1}/
A simple solution that doesn't complicate the regex, but counts the number of matches in a given string:一个简单的解决方案,它不会使正则表达式复杂化,但会计算给定字符串中的匹配数:
function isValid(str) {
return (str.match(/hello/gi) || []).length === 1;
}
This RegEx will match any repeated word:此 RegEx 将匹配任何重复的单词:
(\b\w+\b).+\1
From Regexper.com来自Regexper.com
To check that a string doesn't contain a match:要检查字符串不包含匹配项:
!("testing testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> false
!("testing 1 2 3...".match(/(\b\w+\b).+\1/)) #=> true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.