简体   繁体   English

Javascript匹配一个正则表达式,但不匹配另一个

[英]Javascript match one regex, but not another

How can I find all words in string which 我怎样才能找到字符串中的所有单词
match one expression: 匹配一个表达式:

/[a-zA-Z]{4,}/

but do not match another one: 但不要与另一个匹配:

/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/

Something like pseudocode: 类似伪代码的东西:

string.match( (first_expression) && ( ! second_expression) )

You could just do this: 你可以这样做:

string.match(/[a-zA-Z]{4,}/) && !string.match(/\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b/)

But if you'd like to combine the patterns, you can use a negative lookahead ( (?!...) ), like this: 但是如果你想组合模式,你可以使用负向前瞻(?!...) ),如下所示:

string.match(/^(?!.*\b[a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b).*[a-zA-Z]{4,}.*$/)

But this will reject the whole string if it finds the second pattern—eg "fooz barz" will return null . 但是如果找到第二个模式,这将拒绝整个字符串 - 例如"fooz barz"将返回null

To ensure the words you find do not match the other pattern, try this: 要确保找到的单词与其他模式不匹配,请尝试以下操作:

string.match(/\b(?![a-zA-Z]([a-zA-Z])\1+[a-zA-Z]\b)[a-zA-Z]{4,}\b/)

In this case, "fooz barz" will return "barz" . 在这种情况下, "fooz barz"将返回"barz"

Note that this can be cleaned up a bit by using the case insensitive flag ( i ): 请注意,使用不区分大小写的标志( 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
    }
}

This should match what you want and not what you don't. 这应该符合你想要的,而不是你不想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM