簡體   English   中英

Javascript匹配一個正則表達式,但不匹配另一個

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM