[英]Javascript match one regex, but not another
我怎样才能找到字符串中的所有单词
匹配一个表达式:
/[a-zA-Z]{4,}/
但不要与另一个匹配:
/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/
类似伪代码的东西:
string.match( (first_expression) && ( ! second_expression) )
你可以这样做:
string.match(/[a-zA-Z]{4,}/) && !string.match(/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/)
但是如果你想组合模式,你可以使用负向前瞻 ( (?!...)
),如下所示:
string.match(/^(?!.*\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b).*[a-zA-Z]{4,}.*$/)
但是如果找到第二个模式,这将拒绝整个字符串 - 例如"fooz barz"
将返回null
。
要确保找到的单词与其他模式不匹配,请尝试以下操作:
string.match(/\b(?![a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b)[a-zA-Z]{4,}\b/)
在这种情况下, "fooz barz"
将返回"barz"
。
请注意,使用不区分大小写的标志( i
)可以清除这一点:
string.match(/\b(?![a-z]([a-z])\1+[a-z]\b)[a-z]{4,}\b/i)
if(string.match(first_expression))
{
if(!string.match(second_expression))
{
//Do something important
}
}
这应该符合你想要的,而不是你不想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.