chrs
chrs

Reputation: 6096

Regex to match words with length ranges

I am new to regex and I am having a hard time filtering out words with the length range from 5-7. So here is an example

I have a wordlist, where the words are seperated by whitespace

house computer method position regex avocado

Now let's say I only want words with the length of 5, 6 and 7. The regular expression I am searching for would match anything else.

If I were to replace the matches with nothing I would expect this output.

house method regex avocado

Thanks. :)

E:

I am using this site: http://gskinner.com/RegExr/

Upvotes: 1

Views: 2645

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

You can use {n,m} quantifier, with word boundaries:

\b\w{5,7}\b

It will match a "word" of 5 to 7 alphanumeric characters.

Upvotes: 5

Jerry
Jerry

Reputation: 71538

You could use the regex:

\b(\w{1,4}|\w{8,})\b

And replace by nothing.

See how it works here

After that, you can clean by removing any trailing and double spaces left behind.

Upvotes: 2

Related Questions