You are not logged in.

#1 2013-11-07 08:25:04

cryptkeeper
Member
From: Zurich, Switzerland
Registered: 2011-12-29
Posts: 63

[SOLVED] vim: using special characters like \w inside square brackets

I'm using more and more regexes for my daily programming (constantly asking myself why I haven't started using them much earlier, not only in bash, but also im Vim. Today I've discovered why my expressions containing square brackets (character lists) never worked (in Vim): because special characters, specifically \w, don't seem to be recognized!

These two search expressions should be equivalent:

/[a-zA-Z0-9_]
/[\w]

however they are not, the second expression doesnt find anything. Is there some way to use \w etc. inside square brackets which I've missed, or does that just not work?

Last edited by cryptkeeper (2013-11-07 13:15:17)

Offline

#2 2013-11-07 12:50:34

Trent
Member
From: Baltimore, MD (US)
Registered: 2009-04-16
Posts: 990

Re: [SOLVED] vim: using special characters like \w inside square brackets

Yes, character classes don't nest in Vim. Use it alone:

/\w

You can also use POSIX-style character classes like so:

/[_[:alnum:]]

Every tool has a slightly different interpretation of regular expressions. One thing to be aware of is the "magicness" of Vim's regexes -- do :help magic if you're not familiar. I use \v when I'm doing something complex; it makes the regexes look more like Perl's.

Offline

#3 2013-11-07 13:14:59

cryptkeeper
Member
From: Zurich, Switzerland
Registered: 2011-12-29
Posts: 63

Re: [SOLVED] vim: using special characters like \w inside square brackets

Trent wrote:

Yes, character classes don't nest in Vim. Use it alone:

/\w

You can also use POSIX-style character classes like so:

/[_[:alnum:]]

That's a pity, but at least now I know (I always suspected I was messing up the backslashes before the square brackets until I tried [a-z0-9] and it worked).. SOLVEd then!

Thanks for pointing out POSIX character classes, I didn't know about them, but [a-zA-Z0-9] is pretty much as long.

Trent wrote:

Every tool has a slightly different interpretation of regular expressions. One thing to be aware of is the "magicness" of Vim's regexes -- do :help magic if you're not familiar. I use \v when I'm doing something complex; it makes the regexes look more like Perl's.

Yes I've heard about that. I haven't used it so far, but I guess that would be the next step as I'm using parentheses quite often to reference parts of matches, and these expressions tend to become quite the backslash horror show.

Offline

Board footer

Powered by FluxBB