正则表达式如何匹配出这个字符串'calc(100vh - 420px)'中的数字420
(\d+)(?=px)
const regex = /(\d+)(?=px)/;
const str = `calc(100vh - 420px)`;
let m;
if ((m = regex.exec(str)) !== null) {
// 可以通过变量`m`获取结果
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
可以把这简化为提取数字,然后去取第二个match
值就可以
const str = 'calc(100vh - 420px)';
const regex = /\d+/g;
const matches = str.match(regex);
console.log(matches); // 输出:[ '100', '420' ]
console.log(matches[1]); // 输出 420
假设你的需求是紧接px
的,那:
In [28]: a = 'calc(100vh - 420px)'
In [29]: import re
In [30]: re.findall(r"\d+(?=px)", a)
Out[30]: ['420']
这样就可以取到了啊。
(?=...)
Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example,Isaac (?=Asimov)
will match'Isaac '
only if it’s followed by'Asimov'
.
具体什么规则呢,为什么不能匹配前面的100。如果说是以px结尾的,那可以使用
/\d+(?=px)/