2016-09-27 36 views
-1

我需要「測試」後到來的特定字符串匹配JavaScript的正則表達式匹配任何

  • 前提是有一個(所以避免匹配「測試」獨)
  • ,避免比賽如果該字符串是專門字母 「L」

像這樣

testing rest -> matches (rest) 
testing what -> matches (what) 
testing Loong -> matches (Loong) 
testing N -> matches (N) 
testing L -> this is not matched 
testing LL -> matches (LL) 
testing J -> matches (J) 
testing -> this is not matched 
testing -> this is not matched 
testing L TY -> this specific string will not occur so it is irrelevant 

並加上引號

"testing rest" -> matches (rest) 
"testing what" -> matches (what) 
"testing Loong" -> matches (Loong) 
"testing N" -> matches (N) 
"testing L" -> this is not matched 
"testing LL" -> matches (LL) 
"testing J" -> matches (J) 
"testing" -> this is not matched 
"testing "-> this is not matched 
"testing L TY" -> this specific string will not occur so it is irrelevant 

我該怎麼做?

+0

也許['/ ^「?testing(。{2,}?)」?$ /'](https://regex101.com/r/wI8cY2/2)? –

+0

好吧,也許['/ ^「?testing((?!\ s * L?\ s * $)。*?)」?$ /'](https://regex101.com/r/wI8cY2/3) ? –

+0

'/ ^「(testing(?:)?。*)」$ /' - https://regex101.com/r/cW1dK1/2 – ThePerplexedOne

回答

1

這應做到:

/^testing ([^L]|..+)$/ 

,或者,如果您不能刪除引號匹配前:

/^"?testing ([^L"]|.[^"]+)"?$/ 

釋:

第一部分:^測試搜索你的字符串常量元素 - 這是容易的部分。

然後,有atomic group(在圓形括號中):[^ L] | .. +它由OR聲明(配管)的。

在此的左側,我們對所有一個字符串搜索模式(除了字母「大號」)。這是做定義集(使用方括號[])和否定(使用此符號:^,這意味着否定時,它是第一個簽名方括號)。

在右側,我們搜索任何至少有兩個字符長度的模式。這是通過任何匹配任何東西(使用點號.)並且然後再次執行任何操作來完成的,這次至少一次(通過使用加號:+)。

總結這一點,我們應該得到你所要求的邏輯類型。

+0

「測試生菜」不會匹配 – Gerard

+0

更正的答案,謝謝。 –

+0

但是現在「測試L」將匹配 – Gerard

0

這是你想要的正則表達式。它匹配字符串從測試開始,然後匹配一個或多個空格字符,然後字符大小爲2或更大的字符。

/^testing\s+\w{2,}/ 
+0

我並不是想要匹配2個或更多字母的字符串,我的意思是避免匹配特定的字母L(現在在問題中已澄清) – Gerard

1

我建議在先行基於正則表達式,如果「測試」是字符串結束前,隨後與L和0+空格失敗的比賽:

/^"?testing\s+((?!L?\s*"?\s*$).*?)"?$/ 

regex demo

詳細

  • ^ - 字符串的開頭
  • "? - 任選"
  • testing - 文字字符串testing
  • \s+ - 1以上空格
  • ((?!L?\s*"?\s*$).*?) - 第1組捕獲比換行符符號儘可能少(其他任何0+字符由於懶惰*?,以考慮所述後"以後),但是僅當不等於L(1或零次)或空格,隨後用繩子($的端部)和\s*"?\s*也將佔可選尾隨"
  • "? - 任選"
  • $ - 字符串的結尾。

所以,如果 「測試」 之後與(?!L?\s*$)負先行將無法匹配:字符串

  • 結束
  • L
  • 空格
  • L和空格...

和可選"

var ss = [ '"testing rest"', '"testing what"', '"testing Loong"', '"testing N"', '"testing L"', '"testing"', '"testing "' ]; // Test strings 
 
var rx = /^"?testing\s+((?!L?\s*"?\s*$).*?)"?$/; 
 
for (var s = 0; s < ss.length; s++) {     // Demo 
 
    document.body.innerHTML += "Testing \"<i>" + ss[s] + "</i>\"... "; 
 
    document.body.innerHTML += "Matched: <b>" + ((m = ss[s].match(rx)) ? m[1] : "NONE") + "</b><br/>"; 
 
}

如果您只是想避免在最後匹配「測試」字符串L(之前可選"),你可能會縮短模式

/^"?testing\s((?!L?"?$).*?)"?$/ 

請參閱this regex demo\s由演示中的空格替代,因爲測試是針對多行字符串執行的)

+0

我在前面加了'?\ s *',現在它在最後應該考慮可選的''''。 –

+1

考慮到在我的特殊情況下空間不是可選的,這個簡化版本也可以工作^「?testing((?!L?」?$)。*?)「?$所以非常感謝,需要一段時間理解它:) – Gerard

+0

然而,@TZ的答案也有效,我們會同意,它明確地寫和理解... – Gerard