Is there a pattern like ^ in vim?
Solution 1
There's no shortcut to match the first non-whitespace character on a line, you have to build the pattern yourself, like:
^\s*restofpattern
If you don't want to include the whitespace in your match, you have to use a zero-width assertion, like:
\(^\s*\)\@<=restofpattern
Not exactly pretty, but at least it gets the job done.
Solution 2
To match the first non-whitespace character, you'd just use \S
like you normally do.
If you use ^
in a regex in vim, it will match the actual start of the line, even if it contains whitespace.
For instance, this line starts with a space:
<- there's a space there you can't see :)
This vim command will remove the leading space:
:%s/^ //
resulting in the following:
<- there's a space there you can't see :)
So, the regex will behave as you expect, even if the command doesn't.
Related videos on Youtube
Michael
Updated on September 18, 2022Comments
-
Michael over 1 year
In Vim normal mode, the
0
command takes you to the first column on the line and^
takes you to the logical start of line (e.g. the first non-whitespace character). In the regex world,^
matches the first character on the line, whitespace or not. Does Vim have a pattern that behaves like its '^' command--matching the logical beginning of a line?-
bdsl over 9 yearsI think ^ in a regex normally matches the start of the line, not the first character. ^. will match the start and then the first character, not the start and then the second character.
-
-
Michael over 11 yearsI didn't downvote, but by way of clarification: I was wondering if Vim has an operator to match the first non-whitespace character of the line. The
^
operator (like all sane regex implementations), will match the first character even if it is whitespace. -
Michael over 11 years
\S
will match any non-whitespace character. To put it another way, I'm wondering if Vim has a zero-width shorthand for this:^\W*\S
. -
Michael Hampton over 11 yearsI don't even think regex has something like that.
-
Michael over 11 yearsNo engine that I am aware of provides that functionality, but then again--when would you have cared in a general-purpose engine? Vim isn't a general purpose regex engine. It is an editor that has a regex engine so I was wondering if it had any special constructs for something that only matters inside an editor.