Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing only a part of regexp matching

please consider the following javascript code:

"myObject.myMethod();".replace(/\.\w+\(/g, "xxx");

it gives "myObjectxxx);" as ".myMethod(" is selected.

Now I would only select myMethod instead. In other words I want to select any word starting with . and ending with ( (excluded).

Thanks, Luca.

like image 479
lviggiani Avatar asked Jan 24 '12 22:01

lviggiani


People also ask

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How do you match everything except with regex?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.


1 Answers

General answer: Capture the part that you want to keep with parentheses, and include it in the substitution string as $1.

See any regexp substitution tutorial for details.

Here: just include the . and the ( in your substitution string.

For an exercise, write a regexp that will turn any string of the scheme --ABC--DEF-- to --DEF--ABC-- for arbitrary letter-values of ABC and DEF. So --XY--IJK-- should turn into --IJK--XY--. Here you really need to use capture groups and back references.

like image 59
Has QUIT--Anony-Mousse Avatar answered Sep 19 '22 05:09

Has QUIT--Anony-Mousse