Sublime Forum

Regex replace produces literal result

#1

I’m using ST 3.2.2 on a MacBook Pro, OS 10.15.7. I am editing a text file with regular expressions. Most of the time, the Find/Replace works fine. But I’m encountering a literal replacement issue when attempting to insert a tab after a regex. Here’s the pattern:
Find: ^\D{1,100}
Replace: ^\D{1,100}\t
In other words, look for the 1 to 100 non-digit characters in a line, then insert a tab.Instead Sublime inserts "^D{1,100} " in place of the contents.
Notes: The regular expression button is on. When I was doing Find/Replace and inserting tabs in front of literal characters (for example, Find: County:, Replace: \tCounty:), it worked as expected.

0 Likes

#2

It looks like you’re basically trying to find something and insert text after it, keeping whatever you originally matched still in place? Regular expression replacements don’t follow the same matching pattern rules as the search text does, but you can use captures to do this.

The general idea is that in your search term you can surround the parts of the match that you want to keep to refer to later in () characters to capture them, and then in the replacement text you can refer to the captured items by number; $1 for the first capture, $2 for the second, and so on.

In addition, the whole of the matched text is always available in the capture $0.

So, using the first method, you can search and capture everything, then refer to the first capture in the replacement:

Find: (^\D{1,100})
Replace: $1\t

Or, because in this case you want the whole of whatever is captured to be replaced, you can instead keep the Find: to what you’re already using and just refer to the whole of the matched text in the replace:

Find: ^\D{1,100}
Replace: $0\t

0 Likes

#3

OdatNurd FTW! A simple, elegant solution.

0 Likes