square brackets in regular expression
October 17th, 2006 mysurface Posted in Regular Expression, Text Manipulation, egrep | Hits: 10138 |
Previously we have an example on regular expression, but It doesn’t shows the power of square brackets ( [ ] )
Let say you want to search for string fprintf, vprintf and sprintf using grep, usually what you do is
egrep "fprintf|vprintf|sprintf" *.c
You may be ask why don’t just uses the word “printf”? If uses the word printf, it will return all of them but also include printf itself. But in this case i don’t want to grep other printf besides f,v,s printf. Thats the square brackets comes in to lessen your trouble.
egrep "[sfv]printf" *.c
It simply return the result with any character specified in [ ] with word printf concatenated.
The square brackets can be used with other RE symbols, here is another example, let say I want to gets all lists with words start with a character “a to f”, I can do this
egrep "^[a-f]" com-book.txt
It is case sensitive, I want all a to f including the upper case A to F.
egrep "^[a-fA-F]" com-book.txt
Live Chat!









October 17th, 2006 at 7:25 pm
Why not use the –ignore-case (-i) flag?:
October 17th, 2006 at 7:32 pm
Haha, egrep -i is a good alternative example.
Actually the example above is to show the usage of square brackets in RE :D