簡體   English   中英

JavaScript正則表達式匹配除字母以外的所有內容

[英]JavaScript regex match anything except a letter

我需要匹配“測試”之后的特定字符串

  • 只要有一個(因此避免單獨匹配“測試”)
  • 如果該字符串是字母“ 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

我該怎么辦?

應該這樣做:

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

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

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

說明:

第一部分: ^ testing搜索字符串的常量元素-這很容易。

然后,有一個原子組 (在圓括號中): [^ L] | .. + ,它由OR語句(一個管道)組成。

在該OR的左側,我們為所有一個字符串(字母“ L ”除外)提供了搜索模式。 它是通過定義set(使用方括號[] )和取反(使用此符號^ ,即在方括號中的第一個符號表示否定)來完成的。

在右側,我們可以搜索長度至少為兩個字符的任何內容。 這是通過fisrt匹配所有內容(使用點 ),然后再匹配任何內容(至少一次)(使用加號: + )來完成的。

總結一下,我們應該完全得到您所要求的邏輯。

如果在字符串末尾前加上“ L和0+空格,則“基於測試”的正則表達式會導致匹配失敗:

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

正則表達式演示

詳細資料

  • ^ -字符串開頭
  • "? -可選的"
  • testing -文字字符串testing
  • \\s+ -1個或多個空格
  • ((?!L?\\s*"?\\s*$).*?) -組1捕獲除換行符以外的任何0+字符,並且盡可能少(由於懶惰的*?以解決尾隨的"以后),但只有當不等於L (1或零次)或空格,接着與字符串的結尾( $ )和\\s*"?\\s*也將占到可選尾隨"
  • "? -可選的"
  • $ -字符串結尾。

因此,如果(?!L?\\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?"?$).*?)"?$/

請參閱此正則表達式演示演示中\\s被空格替代,因為測試是針對多行字符串執行的)

這是您想要的正則表達式。 它匹配從測試開始的字符串,然后是一個或多個空格字符,然后是至少2個或更多大小的單詞字符。

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

我相信是您要查找的正則表達式:

/^"(testing(?: )?.*)"$/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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