簡體   English   中英

正則表達式:匹配模式除了前面的模式

[英]Regex: Match patterns except with pattern preceding

我正在嘗試編寫一個正則表達式來匹配某些模式,但前面的模式除外。 換句話說,給出以下句子:

Don't want to match paragraph 1.2.3.4 but this instead 5.6.7.8

我想匹配所有前面沒有單詞paragraph XXXX ,即它應該只匹配5.6.7.8 我當前的正則表達式似乎同時匹配 1.2.3.4 和 5.6.7.8。 我已經切換了前瞻,但似乎與我的用例不匹配。

(?<!paragraph)(?:[\(\)0-9a-zA-Z]+\.)+[\(\)0-9a-zA-Z]+

我用javascript編碼。

編輯:請注意XXXX不是固定在 4 X s。 它們的范圍從XXXXXXX

您的模式匹配,因為“段落”與“段落[空格]”不同。 您的模式沒有空格。 你的文字可以。

您可能希望將空間(可能有條件?)添加到您的后視。 因為你想匹配不同數量的XXXX (你說XXXXXXX ),我們還需要在lookbehind 中包含X.

const rex = /(?<!paragraph *(?:[\(\)0-9a-zA-Z]+\.)*)(?:[\(\)0-9a-zA-Z]+\.){1,4}[\(\)0-9a-zA-Z]/i;

現場示例:

 function test(str) { const rex = /(?<!paragraph *(?:[\\(\\)0-9a-zA-Z]+\\.)*)(?:[\\(\\)0-9a-zA-Z]+\\.){1,4}[\\(\\)0-9a-zA-Z]/i; const match = rex.exec(str); console.log(match ? match[0] : "No match"); } console.log("Testing four 'digits':"); test("Don't want to match paragraph 1.2.3.4 but this instead 5.6.7.8 blah"); console.log("Testing two 'digits':"); test("Don't want to match paragraph 1.2.3.4 but this instead 5.6 blah"); console.log("Testing two 'digits' again:"); test("Don't want to match paragraph 1.2 but this instead 5.6 blah"); console.log("Testing five 'digits' again:"); test("Don't want to match paragraph 1.2 but this instead 5.6.7.8.9 blah");

該表達式要求:

  • paragraph后跟零個或多個空格,可能后跟X. zer 或更多次,不是緊接在匹配之前;
  • X.重復一到四次 ( {1,4} );
  • X緊跟在這三個之后

在我的示例中XA-Z0-9並且我使表達式不區分大小寫,但您可以根據需要進行調整。


請注意,lookbehind 最近才添加到 JavaScript 中,在 ES2018 中,因此支持需要最新的 JavaScript 環境。 如果您需要回顧舊環境,您可以查看 Steven Levithan 的優秀XRegex 庫

另請注意,並非所有語言支持像上述那樣的可變長度后視(但在 JavaScript 中支持......在最新的引擎中)。

如果你總是想匹配一個 4-item 的組,你可以這樣做:

(?<!paragraph )([0-9]+.?){4}

您可以迭代地構建正則表達式 -

  1. 忽略前面帶有“段落”一詞和空格的任何詞。
  2. 由於您的模式是固定的,它將由由句點分隔的四組數字組成,因此可以安全地假設該四組中的最小位數為 1。
  3. 在一個捕獲組中捕獲四組數字以供以后使用。

在這里測試正則表達式。

 const inputData = 'Don\\'t want to match paragraph 1.2.3.4 but this instead 5.6.7.8 and 12.2.333.2'; const re = /(?<!paragraph\\s+)(\\d{1,}\\.\\d{1,}\\.\\d{1,}\\.\\d{1,})/ig; const matchedGroups = inputData.matchAll(re); for (const matchedGroup of matchedGroups) { console.log(matchedGroup); }

暫無
暫無

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

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