将正则表达式缩短为单个匹配组
Shorten the regular expression into a single matching group
目前,我正在使用 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));
}
您可以使用:
(?:\(\) =>|.*return) ([^;\r\n]*)
如果未找到交替的第一侧,引擎将尝试第二侧。如果我们知道一个条件在任何时候都应该满足引擎,贪心点 .*
将使它更早发生。您可能还需要 ^
锚点。
还有第二种方法:
\(\) *=>.* ([^;\r\n]+)
目前,我正在使用 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));
}
您可以使用:
(?:\(\) =>|.*return) ([^;\r\n]*)
如果未找到交替的第一侧,引擎将尝试第二侧。如果我们知道一个条件在任何时候都应该满足引擎,贪心点 .*
将使它更早发生。您可能还需要 ^
锚点。
还有第二种方法:
\(\) *=>.* ([^;\r\n]+)