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

Time:01-17

I need to replace the word 'foo' with the value after the comma for each line - e.g. '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?

CodePudding user response:

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.
  •  Tags:  
  • Related