简体   繁体   中英

Regular expression to replace a value with one from the same line

I need to replace the word 'foo' with the value after the comma for each line - eg 'foo' becomes 'bar1' . The output should look likes this: this.load.image('bar1', bar1);

this.load.image('foo', bar1); 
this.load.image('foo', bar2); 
this.load.image('foo', bar3); 
...

How can this be done with a regular expression?

Search:

\('[^']+',\s*([^\)]+)\);\s*$

Replacement

('$1', $1);

Depending on the text editor, it could be \1 instead of $1 . I use sublime, so I'm not sure which flavor vs code is using.

Explanation:

\(        - Match (
'[^']+',  - Match ', then all text until next ', next ' and the comma
\s*       - Zero or more spaces
([^\)]+)  - Capture group everything up to the next ). the group is important
\);\s*$   - Closing ); then any number of spaces and end of line.

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