1

I have something in a text file that looks like '%r'%XXXX, where the XXXX represents some name at the end. Examples include '%r'%addR or '%r'%removeA. I can match these patterns using regex '%r'%\w+. What I would like to replace this with is '{!r}'.format(XXXX). Note that the name has to stay the same in the replace so I'd get '{!r}.format(addR) or '{!r}.format(removeA). Is there a way to replace parts of the matched string in this way while retaining the unknown variable name pulled out with \w+ in the regex search?

I'm specifically looking for a solution using the find and replace features in Notepad++.

3
  • Is '%r'%XXXX an entire line? If not, describe the context. Does '%r'%XXXX appear more than once in a line? Commented Apr 5, 2016 at 14:36
  • You need capturing groups + backreferences. Commented Apr 5, 2016 at 14:36
  • @Smandoli The text can be located inside a line and more than one may be in a line at a time. Commented Apr 5, 2016 at 14:37

2 Answers 2

2

You can use

'%r'%(\w+)

and replace with '{!r}.format\(\1\)

The '%r'%(\w+) pattern contains a pair of unescaped parentheses that create a capturing group. Inside the replacement pattern, we use a \1 backreference to restore that value.

NOTE: The ( and ) in the replacement must be escaped because otherwise they are treated as Boost conditional replacement pattern functional characters.

See more on capturing groups and backreferences.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Search on:

'%r'%(XXXX)

Replace with:

Whatever You like \1

\1 will match the first set of grouping parentheses.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.