0

I'm trying to grep a list of words and match those that have exactly some letters, no matter the order, but does matter the cuantity, for example, given these letters:

{ a, a, r, f, y, h, l }

over the list

hello
far
hala
miss
cam

should return

far
hala

I don't know if this can be done with regexes or must script something, any aproach is welcome.

3
  • 2
    Character classes. This is so totally googleable.
    – Evan Davis
    Jul 8, 2014 at 20:37
  • 1
    Would "halalala" match, or is it exactly 2 as?
    – Evan Davis
    Jul 8, 2014 at 20:37
  • @Mathletics, as the title says, its exactly 2 'a's. I googled around for tree days and couldnt find the answer to this, maybe using "negative look aheads" (I don't really know what that is) does it. Jul 8, 2014 at 22:42

3 Answers 3

1

Handle the quantity restrictions using negative look aheads, one for each letter, and word boundaries either end of a simple character class

\b(?!([^a\W]*a){3})(?!([^r\W]*r){2})(?!([^f\W]*f){2})(?!([^y\W]*y){2})(?!([^h\W]*h){2})(?!([^l\W]*)l{2})[arfyhl]+\b

See live demo, including matching words within longer lines.

The use of \W stops the look ahead running off the end of the word.

4
  • +1 If OP is looking for the permutation and combination without repeating any letter.
    – Braj
    Jul 8, 2014 at 21:13
  • @Braj just to be clear, a single repetition of a is allowed - notice the different quantity for a (ie not 3). The other letters - yes, one max each
    – Bohemian
    Jul 8, 2014 at 22:47
  • Exactly what I was trying to do! Thanks a lot @Bohemian. Now I've got to lern more about it to fully understand. Jul 8, 2014 at 22:54
  • No problem. Check out this site - it's a great place to learn from. Soon you can be impressing your friends and colleagues with regex Kung Fu
    – Bohemian
    Jul 8, 2014 at 22:58
0

Same approach as Bohemian, just a bit shorter due to the use of back references:

\b(?!\w*([rfyhl])\w*\1|\w*([a])(?:\w*\2){2})[arfyhl]+\b

Fiddle: http://regex101.com/r/gO6dC4/1

0

Alphabetically sort the characters in each word; then you can use a straightforward regex /^a?a?f?h?l?r?y?$/ (make sure the letters in the regex are in alphabetical order).

This AWK script will filter the words on stdin (one word per line):

awk 'function sort(s,z){l=split(s,a,"");asort(a);while(l)z=a[l--]z;return z;}sort($0)~/^a?a?f?h?l?r?y?$/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.