Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

notepad++ regex find, replace and KEEP the match [duplicate]

Ok, before I get the "already answered", I have found and tried every permutation I found at:

While replacing using regex, How to keep a part of matched string?

Using Notepad++ Regex to Find and Replace Only Part of Found Text

I have these lines:

new MyObject("22222,11,21),
new MyObject("22223,12,22),
new MyObject("22224,13,23),
new MyObject("22225,14,24),

I'm trying to put the "end quote" around 22222, 22223, 22224 and 22225 for this:

new MyObject("22222",11,21),
new MyObject("22223",12,22),
new MyObject("22224",13,23),
new MyObject("22225",14,24),

The value I put into notepad++ for "Find What" is working (an escaped double quote plus 5 digits).

\"\d{5}

for "replace with" (based on what I found at the previous two SOF articles), i have tried:

(these are just to test it)

aaa$1bbb
aaa$1$2bbb
aaa$1$2$3bbb

and

aaa\1bbb
aaa\1\2bbb
aaa\1\2\3bbb

Obviously, what I want (and what I think should work) is below (escaped double-quote, then the placeholder for "1", and the a second escaped double-quote)

\"\1\"\

or

\"$1\"\

My search mode is "regular express" and I've toggled ".matches newline" on and off.

Notepad++ v7.7.1 (64-bit)

like image 234
granadaCoder Avatar asked Sep 01 '25 03:09

granadaCoder


2 Answers

You need to capture the match in a capture group:

(\"\d{5})

The replace it with the captured value and a quote:

\1"

e.g.

enter image description here

like image 68
zzevannn Avatar answered Sep 02 '25 21:09

zzevannn


No needs for capture group here, use the following:

  • Ctrl+H
  • Find what: "\d{5}\K(?!") or (?<="\d{5})(?!") (the former doesn't work in Npp when replacing one by one)
  • Replace with: "
  • check Wrap around
  • check Regular expression
  • Replace all

Explanation:

"           # a double quote
\d{5}       # 5 digits
\K          # forget all we have seen until this position
(?!")       # negative lookahead,make sure haven't double quote after

Or

"           # a double quote
(?<=        # positive lookbehind, make sure we have 5 digits before
    \d{5}       # 5 digits
)
(?!")       # negative lookahead,make sure haven't double quote after

Result for given example:

new MyObject("22222",11,21),
new MyObject("22223",12,22),
new MyObject("22224",13,23),
new MyObject("22225",14,24),

Screen capture:

enter image description here

like image 29
Toto Avatar answered Sep 02 '25 22:09

Toto