Reputation: 11
Say I have a regex search that matches what I'm looking for. I need to replace the match with itself plus an additonal word.
Line example:
John
^.*John.*$
This matches what I want (the word John). This is what I need after the replacement:
John abc123
Upvotes: 0
Views: 716
Reputation: 20737
There is no reason to capture everything with .*
Just use:
regex
John
replace
$0 abc123
If you want to avoid turning Johnathan
into John abc123athan
then use word boundaries:
regex
\bJohn\b
replace
$0 abc123
One of the biggest issues with using ^.*John.*$
whatsoever is that if there are two John
s in a single line then only the last one will be replaced.
John has a friend named John
would become
John has a friend named John abc123
Upvotes: 1
Reputation: 1179
You want regex capture groups. Then you can use the capture group as part of what you replace in the string. I'm not sure what syntax Notepad++ uses, so you may need different syntax than this example. See regex101.com to test your regex.
For your example, in python, you can use () to specify the capture group, and r'\1' to use capture group 1 in the new text:
text = 'hello John, how are you'
text = re.sub('([A-Z]\w*)', r'\1' + ' abc123', text)
print(text)
# hello John abc123, how are you
Upvotes: 0