Is there a pattern like ^ in vim?

21

4

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?

Michael

Posted 2012-11-14T19:32:39.163

Reputation: 361

I 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. – bdsl – 2014-12-19T11:28:45.433

Answers

17

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.

Karl Bielefeldt

Posted 2012-11-14T19:32:39.163

Reputation: 1 050

7

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.

Michael Hampton

Posted 2012-11-14T19:32:39.163

Reputation: 11 744

I presume you're going to explain the downvote. This answer, as far as I know, is correct. – Michael Hampton – 2012-11-14T20:08:57.967

1I 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 – 2012-11-14T20:19:45.940

Well, how were you expecting to do it normally? Usually in a regex you would use something like \S to match the first non-whitespace character. – Michael Hampton – 2012-11-14T20:23:36.667

2\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 – 2012-11-14T20:31:43.767

I don't even think regex has something like that. – Michael Hampton – 2012-11-14T20:51:59.723

1No 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. – Michael – 2012-11-14T20:55:53.877