Home » Javascript » Shorten the regular expression into a single matching group

Shorten the regular expression into a single matching group

Posted by: admin October 18, 2018 Leave a comment

Questions:

Currently I am using the RegExp (?:\(\) => (.*)|return (.*);) for a custom nameof function that is called like this: nameof(() => myVariable). Depending on the execution though the lambda is transpiled into something that contains the return myVariable; part therefore I need an alternative branch looking for return.

The transpiled output will be of the form ()=>{cov_26zslv4jy3.f[9]++;cov_26zslv4jy3.s[38]++;return options.type;}.

Examples are the following:

// 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;}

My current RegExp works however it has two matching groups depending on the type of whether the lambda was transpiled or not. Is it possible to rewrite the expression such I have a single matching group which will contain the name?


For further details, I have attached the full code of my function:

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));
}
Answers: