meisterluk’s advent calendar: additions to regex, :s and :g

Ok… writing long regex’ and using this stupid :%s///g is very annoying. Actually it’s not usable and some features allow you to optimize your work with it.

~ The tilde is a alias for the regex used in the last search. Available in normal searches (via slash) and substitution commands.
n This sequence allows you to access subclasses. For example :%s/(rat)ing/1e/g will replace all “rating”s with “rate”. Note: n is the number of the subclass of the regex
Escaping character. For example 1 is not a regex subclass; this is simply “1″.
& Will be replaced with to whole match. For example :%s/./&/g will replace each character with itself.
l u The character following l will be converted to lowercase; the character following u to uppercase.
L U Like l and u it converts characters. But this affects the whole term. :%s/Home/U&/g will replace “Home” to “HOME” everywhere.

Beside all those special characters, another problem are [brackets]. I mean, it’s very useful to define range to match different characters, but it might be frustrating: [a-z] does not match é and a simple dot also matches numbers. To match é, but ignore numbers, you have two different possibilities (the slash introduces a search):

/[^0-9]

This regex matches anything except numbers. The other possibility is to define a character class:

[:alnum:] alphanumeric characters
[:alpha:] alphabetic characters
[:blank:] whitespace characters (like space, tabulator)
[:cntrl:] control characters
[:digit:] numeric characters [0-9]
[:graph:] all characters except whitespaces
[:lower:] lowercases
[:print:] printable characters (including spaces)
[:punct:] punctuation marks
[:space:] all whitespace characters
[:upper:] uppercases
[:xdigit:] characters for hexadecimal numbers

You can use these classes to match characters, you might have not available on your keyboard. The solve the problem from above, you have to negotiate a character class (yes, you can do this): /[^[:digit:]]

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>