square brackets in regular expression

October 17th, 2006 mysurface Posted in egrep, Regular Expression, Text Manipulation | Hits: 89882 | 7 Comments »

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

7 Responses to “square brackets in regular expression”

  1. Why not use the –ignore-case (-i) flag?:

    egrep -i "^[a-f]" com-book.txt
  2. Haha, egrep -i is a good alternative example.

    Actually the example above is to show the usage of square brackets in RE :D

  3. Unquestionably believe that which you stated. Your favorite justification appeared to be on the web the simplest thing to be aware of. I say to you, I definitely get annoyed while people consider worries that they just do not know about. You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could take a signal. Will probably be back to get more. Thanks

  4. It’s a shame you don’t have a donate button! I’d without a doubt donate to this fantastic blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this website with my Facebook group. Chat soon!

  5. Hello my friend! I want to say that this post is amazing, nice written and include almost all vital infos. I would like to see more posts like this .

  6. Porsha Berlacher Says:

    @FinestWun4U It is best to check out this girl intreegme who is also transitioning to help healthy hair. Just seek intreegme on vimeo… she has a great system concoction that i REALLY ENJOY implementing Ausie’s conditioner!

  7. I quite like looking through a post that can make people think.
    Also, many thanks for permitting me to comment!

Leave a Reply