sunny8107
sunny8107

Reputation: 409

how do I match words of specific sizes using Regular Expressions?

I have a file called file.txt with say 3 words

ban
moon
funny

Now I want to match only the words with 3 or 4 characters

grep "[a-z]\{3,4\}" file.txt

This is not working..it stil matches all the 3 words, I was expecting only to match the first 2. What am I doing wrong here?

Upvotes: 0

Views: 133

Answers (3)

chryss
chryss

Reputation: 7519

A word with 5 characters matches [a-z]{4}. You need word boundaries, and egrep:

chris$ egrep "\b[a-z]{3,4}\b" regextest.txt 
ban 
moon 
chris$

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185980

Use this:

grep "\<[a-z]\{3,4\}\>" file.txt

Upvotes: 2

Scott Saunders
Scott Saunders

Reputation: 30414

That matches every three or four letter combination. What you want is to match every three or four letter combination that is bounded by whitespace or the start or end of a line.

Upvotes: 0

Related Questions