How to Replace Text Surrounding Text in Notepad++&

2019-08-16 18:29发布

问题:

This question is the opposite from other regex notepad++ questions. Instead of changing text between text, I need to replace text that is surrounding, like that:

from

$_REQUEST['action']

to

getReq('action')

So:

I wish to replace $_REQUEST( for getReq( and at same time replace ] for ).

How can I achieve that in Notepad++ ? There are more than a 1000 hits and I want to replace it all, not just the ones with action index, but many more!

回答1:

You still want to match, you just want match with capture (Notepad supports this, make sure Regex is checked in search and replace. The ( ) is the capture group, the order of the first ( is the capture group number. (?: ) can be used to make a group non-capture)

Match on \$_REQUEST\['([^']*)'\]

Replace using capture with getReq\('$1'\)

EDIT: In Notepad, you have to escape () for some reason in the replace part



回答2:

You need to use a capturing group in your regex. In most regex engines, capturing groups are indicated with parentheses, possibly escaped with backslashes in front:

foo(capturing_group)bar

foo\(capturing group\)bar

Notepad++ uses PCRE, I think, so it should be bare parens (the first example, above).

What you have is a larger pattern:

$_REQUEST['some variable text goes here']

You want to replace that with

getReq('some variable text goes here')

The capturing group will "capture" (or "save") the variable text, and a backreference to the group will "insert" the text in your replacement:

$_REQUEST['([^']*)']   

getReq('\1')

The search would be for the outside text, $_REQUEST[' and '], plus a capturing group ( ... ) containing [^']* any number of characters that are not single quotes.

The replacement would be the outside replacement text, getReq(' and '), plus a backreference to the first (and only!) capturing group in the original match. The \1 is replaced by everything matched inside the first set of parens.

FYI: Groups are generally numbered by counting opening parentheses. So a nested group like this: ( ( ) ) ( ( ) ) would be numbered (1 (2 ) ) (3 (4 ) ).