Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep regex to unscramble a word

Tags:

regex

grep

I want to unscramble a word using the grep command.

I am using below code. I know there are other ways to do it, but I think I'm missing something here:

 grep "^[yxusonlia]\{9\}$" /usr/share/dict/words

should produce one output:

anxiously

but it produces:

annulosan                      
innoxious

and many more. Basically I can't find how I should specify that characters can only be matched once, so that I get only one output.

I apologise if it seems very simple but I tried a lot and can't find anything.

like image 202
hsdhillon Avatar asked Feb 13 '23 17:02

hsdhillon


2 Answers

You can use grep -P (PCRE regex) with negative lookahead

grep -P '^(?:([yxusonlia])(?!.*?\1)){9}$' /usr/share/dict/words
anxiously 

Explanation:

This grep regex uses negative lookahead (?!.*?\1) for each character matched by group #1 i.e. \1. Each character is matched only and only when it is not followed by the same character again in the string till the end.

like image 111
anubhava Avatar answered Feb 15 '23 11:02

anubhava


You can use lookaheads to make sure that each letter is matched exactly one time. It is verbose and requires a version of grep that supports lookaheads (e.g. via -P). It may be better to build the search string programmatically.

grep -P "^(?=.*y)(?=.*x)(?=.*u)(?=.*s)(?=.*o)(?=.*n)(?=.*l)(?=.*i)(?=.*a)[yxusonlia]{9}$" /usr/share/dict/words
like image 40
Explosion Pills Avatar answered Feb 15 '23 09:02

Explosion Pills