【问题标题】:Regex pattern with variable not working带有变量的正则表达式模式不起作用
【发布时间】:2018-07-29 14:07:31
【问题描述】:

以下正则表达式正确提取引号之间的路径。

const value = 'image-width("image-path.jpg")';
const result = value.match(/image-width\(['"]?(.+?)['"]?\)/)[1];

console.log(result); // image-path.jpg

但我需要让它更干燥,因为image-width 可能并不总是相同,所以我创建了一个函数,使image-width 成为一个变量

function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`; // deliberate double back slash
    const patternMatch = new RegExp(regexString, 'g'); // /image-width\(['"]?(.+?)['"]?\)/g (which is the same as the working regex value above
    return value.match(patternMatch)[1]; // undefined
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // undefined

这不起作用,path 只是未定义。

【问题讨论】:

  • replace 不会出现在给定代码中的任何地方
  • @GeorgeJempty 抱歉,我已将问题的最后一部分修改为 path 只是未定义。
  • 在我看来你得到 0 个匹配项,所以也许你的正则表达式是错误的? patternMatch 的值究竟是什么?
  • @AndréKool patternMatch == /image-width\(['"]?(.+?)['"]?\)/g 与上面的第一个工作正则表达式相同(减去末尾的g 修饰符)

标签: javascript regex concatenation


【解决方案1】:

问题在于 match()g 修饰符一起使用

使用.match()破解

function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`;
    const patternMatch = new RegExp(regexString, 'g');
    return value.match(patternMatch)[1];
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // undefined

使用.exec() 修复

function getPath(value, wrapper) {
    const regexString = `${wrapper}\\(['"]?(.+?)['"]?\\)`;
    const patternMatch = new RegExp(regexString, 'g');
    return patternMatch.exec(value)[1]; // Use exec() instead
}

const path = getPath('image-width("image-path.jpg")', 'image-width'); // image-path.jpg

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2015-03-02
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多