正则表达是如何匹配到这个数字?

正则表达式如何匹配出这个字符串'calc(100vh - 420px)'中的数字420

阅读 921
4 个回答

具体什么规则呢,为什么不能匹配前面的100。如果说是以px结尾的,那可以使用/\d+(?=px)/

(\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}`);
    });
}

image.png

可以把这简化为提取数字,然后去取第二个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

image.png

假设你的需求是紧接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'.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进