Reputation: 6066
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.
Upvotes: 19
Views: 33353
Reputation: 178
That's awesome thank you Has QUIT--Anony-Mousse!
I wanted 123456,SomeText to become 123456,InsertedText,SomeText.
What I did to solve this is below. Credit to "Has QUIT--Anony-Mousse" above. I'm just giving a clear example of how to implement his solution.
Find:
(123456),SomeText
Replace:
$1,InsertedText,SomeText
And the result you will get from this find and replace using Regex is:
123456,InsertedText,SomeText
By using the parentheses around 123456, it basically assigned 123456 to a variable that I was able to use by using "$1" in the replace. Hope that makes sense. Thanks again!
Upvotes: 1
Reputation: 77454
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.
Upvotes: 38
Reputation: 44349
I'd suggest a slightly different approach:
"myObject.myMethod();".replace(/^([^\.]*\.)\w+(\(.*)$/g, "$1xxx$2");
though simpler solutions have been suggested.
Upvotes: 2
Reputation: 354426
You can use lookaround assertions:
.replace(/(?<=\.)\w+(?=\()/g, 'xxx')
Those will allow the match to succeed while at the same time not being part of the match itself. Thus you're replacing only the part in between.
The easier option for people unfamiliar with regexes is probably to just include the .
and (
in the replacement as well:
.replace(/\.\w+\(/g, ".xxx(")
Upvotes: 10