【问题标题】:Shorten the regular expression into a single matching group将正则表达式缩短为单个匹配组
【发布时间】:2018-05-22 22:52:41
【问题描述】:

目前,我正在使用 RegExp (?:\(\) => (.*)|return (.*);) 来实现自定义 nameof 函数,该函数的调用方式如下:nameof(() => myVariable)。根据执行情况,尽管 lambda 被转译为包含 return myVariable; 部分的内容,因此我需要一个替代分支来寻找 return

转译后的输出格式为()=>{cov_26zslv4jy3.f[9]++;cov_26zslv4jy3.s[38]++;return options.type;}

示例如下:

// should return "foo"
() => foo
// should return "foo.bar"
() => foo.bar
// should return "options.type"
()=>{cov_26zslv4jy3.f[9]++;cov_26zslv4jy3.s[38]++;return options.type;}

我当前的 RegExp 可以工作,但是它有两个匹配组,具体取决于 lambda 是否被转译的类型。是否可以重写表达式,使我有一个包含名称的匹配组?


更多详情,我附上了我的函数的完整代码:

const nameofValidator: RegExp = new RegExp(/(?:\(\) => (.*)|return (.*);)/);

/**
 * Used to obtain the simple (unqualified) string name of a variable.
 * @param lambda A lambda expression of the form `() => variable` which should be resolved.
 */
export function nameof<TAny>(lambda: () => TAny): string {
    const stringifiedLambda: string = String(lambda);
    const matches: RegExpExecArray | null = nameofValidator.exec(stringifiedLambda);
    if (matches === null) {
        throw new ArgumentException("Lambda expression must be of the form `() => variable'.", nameof(() => lambda));
    }

    if (matches[1] !== undefined) {
        return matches[1];
    }
    if (matches[2] !== undefined) {
        return matches[2];
    }

    throw new ArgumentException("Lambda expression must be of the form `() => variable'.", nameof(() => lambda));
}

【问题讨论】:

  • @revo 这是一个错误,我删除了标签。感谢您指出这一点。
  • 你不能用(?:\(\) =&gt;|return) ([^;]*)吗?
  • @revo 它似乎朝着正确的方向前进,但即使专门添加了/s 选项,它目前也匹配多行。
  • @revo 你可能误读了我的转译输出 - 我已经添加了更多带有预期值的示例。

标签: javascript regex regex-group


【解决方案1】:

你可以使用:

(?:\(\) =>|.*return) ([^;\r\n]*)

如果没有找到交替的第一面,引擎会尝试第二面。如果我们知道一个条件应该在任何时候满足引擎,贪婪点.* 将使它更早发生。你可能也需要^ 锚。

Live demo

还有第二种方法:

\(\) *=>.* ([^;\r\n]+)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 2012-11-21
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多