给定 myString 6 cyl, 3.2L (3197cc) 引擎
,需要提取以下内容:6 cyl
和 3197cc
。
此代码失败,不知道如何修复它。
const rgx = /(\d cyl).*(\d{2,4}?cc)/g; //defined outside a loop
//inside the loop we have myString changes every run.
let match = rgx.exec(myString);
console.log(match[1]); // => 6 cyl
console.log(match[2]); // => 97cc <--------- suppose to be 3197cc
然后下一个循环,整个事情都无法匹配说
"Cannot read property '1' of null".
我做错了什么?
最佳答案
您没有匹配周围的括号,这导致正则表达式匹配可能的最小匹配(贪婪与非贪婪)
将您的正则表达式更改为:
/(\d cyl).*\((\d{2,4}cc)\)/g
我从 \d{2,4}
中删除了 ?
因为根据您所写的内容,听起来需要 cc 大小(如果你确实希望它是可选的,你可能也希望 cc 是可选的)
然后在 \((\d{2,4}cc)\)
上,我添加了外部括号,前面有一个反斜杠。这是与括号的字面匹配,现在正则表达式可以正常工作。
const rgx = /(\d cyl).*\((\d{2,4}cc)\)/g; //defined outside a loop
//inside the loop we have myString changes every run.
let match = rgx.exec('6 cyl, 3.2L (3197cc) engine');
console.log(match[1]); // => 6 cyl
console.log(match[2]); // => 97cc <--------- suppose to be 3197cc
关于javascript - 使用正则表达式提取某些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40034613/