Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store regex match in a variable to use with Search/Replace in Notepad++

I need to capture a word using a pattern and store somewhere to use in replace operation:

For instance I have this text

ab iiids
as sasas
md aisjaij
as asijasija

I am able to capture everething before the first space using the following pattern:

.*?(?=[" "])

Let´s say I could use '$' to represent the match in the search and replace so I would like to have the following in the replace field

INSERT INTO table (value) VALUES ("$")

Could not find a solution. Is this even possible?

like image 712
Guilherme Longo Avatar asked Mar 24 '23 09:03

Guilherme Longo


1 Answers

Yes, $& or $0 represents the entire match in the replacement string:

Find what: .*?(?=[ ])
Replace with: INSERT INTO table \(value\) VALUES \("$0"\)

Note that you don't need the quotes inside the character class. Otherwise your match will stop at a quote as well. Also note, that there is another catch, that you have to escape parentheses in the replacement string (thanks to acdcjunior for noticing that). That's because Notepad++ uses boost, which supports a parenthesis-delimited conditional construct.

Using your input, this will result in

INSERT INTO table (value) VALUES ("ab") iiids
INSERT INTO table (value) VALUES ("as") sasas
INSERT INTO table (value) VALUES ("md") aisjaij
INSERT INTO table (value) VALUES ("as") asijasija

For more advanced use cases, you can wrap parts of the regex in parentheses, and reference the substrings they matched with $1, $2, and so on.

By the way, a more explicit pattern would be:

^[^ ]*(?=[ ])

This makes sure that you don't get additional matches where you don't want them.

Finally, here is a reference of all the things you can do in the replacement string.

like image 139
Martin Ender Avatar answered Mar 25 '23 21:03

Martin Ender