Sublime Forum

Regex Find/Replace Entire Line Bug

#1

Hi,

I’m not entirely positive this is a bug, but the behavior is non-intuitive if it is not. Basically if you try to replace an entire line without using the start and end line characters, the replace expression will will be duplicated at the end of the line. Here is an example:

Editor text: Sublime

Find what: (.*)
Replace with: (\1)

Result: (Sublime)()

In order to get (what I believe is) the correct behavior, you need the following:

Editor text: Sublime

Find what: ^(\1)$
Replace with: (\1)

Result: (Sublime)

It looks as though its also matching some invisible character at the end of the line? I’m not sure what causes this type of behavior or if it would manifest itself somewhow in other expressions, I just thought I’d report it.

Thanks!
Bryan

0 Likes

#2

[quote]Editor text: Sublime

Find what: (.*)
Replace with: (\1)

Result: (Sublime)()[/quote]

Regex patterns can be very non-intuitive, but I think this one is working as expected. The (.)* pattern first matches the whole line ‘Sublime’. But then it additionally matches nothing at the end of the line (.** matches any character zero or more times). There are at least two solutions. First you can require that the match to be at start of line with pattern ^(.) or alternatively you can require a match of at least one character with pattern (.+)

The difference here is that the first pattern matches all lines but the second pattern only matches non-empty lines.

0 Likes

#3

Thanks for your reply. I’ve tested this against vim, emacs, notepad++, kate, and gedit, perl, and sed (redundant, I know). Each one of these performs the replacement the way that I proposed as ‘correct’. This may be an issue with the underlying libraries that sublime is using, however I believe it is still an issue. Many editors (Visual Studio anyone?) play fast and loose with Regular Expressions, and while sublime’s find and replace capabilities have proved quite nice thus far and I don’t see it going down that path in any way, I would just like to make sure that this problem is known so that it can be addressed.

I know that this is a little bit nit picking on my part, but to me a good regex find/replace is the most important part of an editor hands down, and since sublime isn’t cross platform (yet), I don’t want to have to remember any special cases about regex evaluation that will need to be applied differently across the editors that I use.

0 Likes

#4

Agreed, that sounds reasonable. Although the current behavior is understandable from programmer’s point of view, it doesn’t really make sense for the user that Sublime makes a second replacement (matching nothing) at end of the line. It would be best to make the regex behavior in Sublime similar to the other editors. Until then using ^(.)* should be a decent workaround.

0 Likes

#5

I’ll fix this for the next beta

0 Likes