[英]Match only if conditions are true
我想獲得在JavaScript中進行正則表達式匹配的幫助
僅匹配數字:
我將在TEXT中使用它:
29% OK
First | Cocoa Apples are
23% NOT
Second | Test Text
18% NOT
Third | Mango Alpa Tango
16% NOT
Fourth | Apples are
33% OK
Fifth | Text Testing App
10% NOT
Sixth | Apples are Gold Duck
28% OK
Seventh | Alpa Apples are Tango
66% OK
Eighth | Oh My Apples are Avocado
20% NOT
Ninth | This Is My Text
25% NOT
Tenth | This Is Hard
嘗試這個:
/(2[5-9]|[3-9][0-9])%(?=.*\n.*Apples)/g
不確定正則表達式,但我認為以下內容在查找數字和行方面做得很好:
var str = `29% OK First | Cocoa Apples are 23% NOT Second | Test Text 18% NOT Third | Mango Alpa Tango 16% NOT Fourth | Apples are 33% OK Fifth | Text Testing App 10% NOT Sixth | Apples are Gold Duck 28% OK Seventh | Alpa Apples are Tango 66% OK Eighth | Oh My Apples are Avocado 20% NOT Ninth | This Is My Text 25% NOT Tenth | This Is Hard`; var bigger = false; str.split("\\n").forEach(function(row, i) { if (i % 2 == 0 && parseInt(row.replace(/\\\\D/g, ""), 10) >= 25) { bigger = true; } else { if (bigger) { bigger = false; if (row.indexOf("Apples") > -1) { console.log("match in line " + i ); } } } });
在這里,它應該按您的要求工作
^(?:(?:.*\n){2})*?((?:2[6-9]|[3-9][0-9]|100)).*\n.*Apples
說明
^(?:(?:.*\\n){2})*?
匹配零行或偶數行,
((?:2[6-9]|[3-9][0-9]|100))
組變量\\1
大於25的百分比,
.*\\n.*Apples
匹配行包含單詞"Apples"
。
看, 演示
請注意,由於javascript中向后查找的某些限制,捕獲百分比數量比僅匹配百分比要方便得多。
一些更直接的方法
(?:2[6-9]|[3-9][0-9]|100)(?=.*\n.*Apples)
我認為這種方法比第一種更容易,因為您不需要處理“奇數”或“偶數”之類的奇特詞。
看, 演示
采用
(2[5-9]|[3-9][0-9]|100)%.*\n.*Apples.*
如果您需要捕獲所有文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.