【问题标题】:How to check if regex matches whole string in javascript? [duplicate]如何检查正则表达式是否与javascript中的整个字符串匹配? [复制]
【发布时间】:2018-05-01 14:16:29
【问题描述】:

如果给你一个像"foo bar 32536364" 这样的字符串和一个正则表达式/foo bar \d+/,你如何检查正则表达式是否匹配完整的字符串而不是字符串中的某些子字符串?我也无法更改输入值,例如输入^$

谢谢

【问题讨论】:

标签: javascript regex


【解决方案1】:

您可以将源的长度与匹配项进行比较,也可以将匹配的字符串与源进行比较,如果它们相同,则您匹配了整个字符串,而不仅仅是其中的一部分:

let source1 = "foo bar 12345";
let source2 = "foo bar 12345 foo";

let match1 = source1.match(/foo bar \d+/);
let match2 = source2.match(/foo bar \d+/);

console.log(match1[0] === source1);
console.log(match1[0].length === source1.length);

console.log(match2[0] === source2);
console.log(match2[0].length === source2.length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    相关资源
    最近更新 更多