Need a regex expression finds all the words of length 8 that contain a and e

Viewed 142

I'm just using a grep command to do this. I'm not sure how to write the regex expression to find all words of length 8 that contain specific letters a and e anywhere in the string.

\b\w{8}\b - gets all the 8 character words but how do you further filter to remove all those that don't contain a or e.

elephant - good
elafna   - bad  too short
aassdddd - bad needs to contain e
2 Answers

If grep -P is supported to make use of PCRE regex, you could use

\b(?=\w{8}\b)(?=\w*a)\w*e\w*\b

Explanation

  • \b Word boundary
  • (?=\w{8}\b) Positive lookahead, assert 8 word chars followed by a word boundary directly to the right
  • (?=\w*a) Positive lookahead, assert an a char to the right
  • \w*e\w* Match 0+ times a word char, match an e char and again 0+ times a word char
  • \b Word boundary

Regex demo

For example

grep -oP "\b(?=\w{8}\b)(?=\w*a)\w*e\w*\b" words.txt

Output

elephant

Use

grep -oE '\b[[:alnum:]_]{8}\b' words.txt | grep '[ae]'

The \b[[:alnum:]_]{8}\b pattern matches 8-word character words and then the second grep only keeps those words that contain either a or e letter.

Test:

grep -oE '\b[[:alnum:]_]{8}\b' <<< 'sed45678 bash_123 qw3rtyui' | grep '[ae]'

Result:

sed45678
bash_123
Related