简体   繁体   中英

Regex to find and replace where the Key is the same as Value {foo:foo} to {foo}

Summary: Use regex with place holders to find where the key and value are the same, and replace with just the key (in my case leveraging ES6 object-property shorthand syntax to clean thousands lines of broken ES5 code - where I can't find an auto helper in eslint rules for use with --fix).

Example:

module.exports = {
    foo: foo,
    bar: bar,
    baz: someFunctionNotCalledBaz,
    someOther: () => console.log('Defined directly. Not a reference to same name function.')
};

What I want (cleaning up old, broken code and ES6'ing a NodeJS project):

module.exports = {
    foo,
    bar,
    baz: someFunctionNotCalledBaz,
    someOther: () => console.log('Defined directly. Not a reference to same name function.')
};

I'm pretty familiar with regex, and I'm not sure this is even be possible. Using Vim, or an IDE Replace w/ regex I'd like to find a way to say:

Find all "word: word", regardless of spaces, and then the matching key on the value side:

(\w+)(:{1}\s{0,})(*SOMEHOW_REFERENCE_FIRST_MATCHING_GROUP_WITHIN_FIND*)

Replace with reference (using placeholder that would already work with matching group):

$1

Is this "lookback" even possible within the same regex? I did look at a bunch of other posts that matched my query, but to no avail.

This should do it:

sed -E 's/(.+): \1/\1/g' file

If you're unfamiliar with sed , the first part will look for strings that match the pattern (.+): \1 , and the second part will replace it with \1

The \1 you see are backreferences, they refer to a capturing group. A capturing group is text inside parenthesis (here, (.+) ).

(.+): \1 will locate any string of 1 or more characters followed by a semicolon and a space, and then the same string again.

And finally, sed will replace any matching string with \1 , which is the part before the semicolon.

Hope this makes sense!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM