I'd like to get help with making a Regex match in JavaScript
Match the number only:
The TEXT I will be using it with:
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
Not sure about a regex, but I think the following does a pretty good job with finding the numbers and lines:
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 ); } } } });
Here, it should work as your request
^(?:(?:.*\n){2})*?((?:2[6-9]|[3-9][0-9]|100)).*\n.*Apples
Explanations
^(?:(?:.*\\n){2})*?
match zero line or even number of lines,
((?:2[6-9]|[3-9][0-9]|100))
group number of percentage which larger than 25 to variable \\1
,
.*\\n.*Apples
match line that has the word "Apples"
.
see, DEMO
Note that because of some limitation of lookbehind in javascript, it's much more convenience to capture number of percentage than just match it.
Some more straightforward way
(?:2[6-9]|[3-9][0-9]|100)(?=.*\n.*Apples)
I think this approach is more easy than the first one because you don't need to deal with such fancy words like "odd" or "even".
see, DEMO
Use
(2[5-9]|[3-9][0-9]|100)%.*\n.*Apples.*
if you need to capture all text.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.