Regular expression search replace in Sublime Text

2019-01-09 20:59发布

问题:

I'm looking to do search replace with regular expressions in Sublime Text 2. The documentation on this is rather anemic. Specifically, I want to do a replace on groups, so something like converting this text:

Hello my name is bob

And this search term:

Find what: my name is (\w)+

Replace with: my name used to be $(1)

The search term works just fine but I can't figure out a way to actually do a replace using the regexp group.

回答1:

Usually a back-reference is either $1 or \1 (backslash one) for the first capture group (the first match of a pattern in parentheses). So maybe try:

my name used to be \1

or

my name used to be $1

UPDATE: As several people have pointed out, your original capture pattern is incorrect and will only capture the final letter of the name rather than the whole name. You should use the following pattern to capture all of the letters of the name:

my name is (\w+)


回答2:

By the way, in the question above:

For:

Hello, my name is bob

Find part:

my name is (\w)+

With replace part:

my name used to be \1

Would return:

Hello, my name used to be b

Change find part to:

my name is (\w+)

And replace will be what you expect:

Hello, my name used to be bob

While (\w)+ will match "bob", it is not the grouping you want for replacement.



回答3:

Use the ( ) parentheses in your search string

There is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be embraced by ( ) parentheses, otherwise these matched segments won't be reachable with variables such as $1, $2,...nor \1, \2,.. and etc.

EXAMPLE:

We want to replace 'em' with 'px' but preserve the number values:

margin: 10em
margin: 2em

So we use the margin: $1px as the replacement string.


CORRECT: Embrace the desired $1 matched segment by ( ) parentheses as following:

FIND: margin: ([0-9]*)em (With parentheses)

REPLACE TO: margin: $1px

RESULT:

margin: 10px
margin: 2px

WRONG: The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1:

FIND: margin: [0-9]*em (Without parentheses)

REPLACE TO: margin: $1px

RESULT: ($1 is undefined)

margin: px
margin: px


回答4:

Here is a visual presentation of the approved answer.



回答5:

Note that if you use more than 9 capture groups you have to use the syntax ${10}.

$10 or \10 or \{10} will not work.