Home Download Buy Blog Forum Support

Regex search single line , remove leading spaces

Regex search single line , remove leading spaces

Postby Jim on Sun Mar 04, 2012 8:13 pm

I am confused.

This is 2181 on windows XP

I want to search and remove leading spaces by using smtg like "^\s+(\w.+)$", "$1"

But Sublime always match greedy multi lines and remove line break too and not spaces only?


Example (dots indicate space here):

Code: Select all
Start


Line number one


..Second line here

..Third line



gives me:
Code: Select all
Start
Line number one
Second line here
Third line


instead of wanted:
Code: Select all
Start


Line number one


Second line here

Third line



What do i wrong?

.
Jim (on Windows Win7, now finally with ST3)
Jim
 
Posts: 40
Joined: Sun Feb 26, 2012 5:21 pm

Re: Regex search single line , remove leading spaces

Postby facelessuser on Sun Mar 04, 2012 9:01 pm

Do this:

Code: Select all
^[^\S\r\n]+(\w.+)$


That should give you what you want.

\s was including \r\n, by saying do not include things other than whitespace (\S) and do not include newlines (\n) and carriage returns (\r), you are getting left with just tabs and spaces, or what you thought you were getting with \s. \s includes line breaks.

Edit
Alternatively you could just say, only tabs and spaces.

Code: Select all
^[ \t]+(\w.+)$

Both work just fine. Not sure why my brain picked the first over this. My brain seems to gravitate to the more obscure solution first...oh well. :)
facelessuser
 
Posts: 1575
Joined: Tue Apr 05, 2011 7:38 pm

Re: Regex search single line , remove leading spaces

Postby Jim on Sun Mar 04, 2012 10:18 pm

Thank you.

Your regex works of course.
^[ \t]+?(\w.+)


And true is, "\s includes line breaks."
And SublimeText does an good job here, i like this.



But why didn't SublimeText have the option to let the ^ caret match at start of (an single) line ?

^ (caret)

Matches at the start of the string the regex pattern is applied to.
Matches a position rather than a character.
Most regex flavors have an option to make the caret match after line breaks
(i.e. at the start of a line in a file) as well.

^. matches a in abc\ndef.
Also matches d in "multi-line" mode.


From http://www.regular-expressions.info/reference.html



At least "^\s+?(\w.+)" should match non-greedy an single line only, isn't it?.






But i think SublimeText behave like
(?m)
Caret and dollar match after and before newlines for the remainder of the regular expression.
(Older regex flavors may apply this to the entire regex.)


Then i think the flag (?-m) should disable this, but that doesn't work.



What do others think about this behaviour? Am i only wrecked by the weak RE implementation of other editors :lol: ?


.
Jim (on Windows Win7, now finally with ST3)
Jim
 
Posts: 40
Joined: Sun Feb 26, 2012 5:21 pm


Return to General Discussion

Who is online

Users browsing this forum: No registered users and 19 guests