[英]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。 它們的范圍從XX
到XXXXX
您的模式匹配,因為“段落”與“段落[空格]”不同。 您的模式沒有空格。 你的文字可以。
您可能希望將空間(可能有條件?)添加到您的后視。 因為你想匹配不同數量的XXXX
(你說XX
到XXXXX
),我們還需要在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
緊跟在這三個之后在我的示例中X
是A-Z0-9
並且我使表達式不區分大小寫,但您可以根據需要進行調整。
請注意,lookbehind 最近才添加到 JavaScript 中,在 ES2018 中,因此支持需要最新的 JavaScript 環境。 如果您需要回顧舊環境,您可以查看 Steven Levithan 的優秀XRegex 庫。
另請注意,並非所有語言都支持像上述那樣的可變長度后視(但在 JavaScript 中支持......在最新的引擎中)。
如果你總是想匹配一個 4-item 的組,你可以這樣做:
(?<!paragraph )([0-9]+.?){4}
您可以迭代地構建正則表達式 -
在這里測試正則表達式。
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.