Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match the alphanumeric words(NOT NUMERIC-ONLY words) which have unique digits

Using regular expression, I want to select only the words which:

  • are alphanumeric
  • do not contain only numbers
  • do not contain only alphabets
  • have unique numbers(1 or more)

I am not really good with the regex but so far, I have tried [^\d\s]*(\d+)(?!.*\1) which takes me nowhere close to the desired output :(

Here are the input strings:

I would like abc123 to match but not 123.
ab12s should also match
Only number-words like 1234 should not match
Words containing same numbers like ab22s should not match
234 should not match
hel1lo2haha3hoho4
hel1lo2haha3hoho3

Expected Matches:

abc123
ab12s
hel1lo2haha3hoho4
like image 378
ManJoey Avatar asked Feb 02 '19 06:02

ManJoey


1 Answers

You can use

\b(?=\d*[a-z])(?=[a-z]*\d)(?:[a-z]|(\d)(?!\w*\1))+\b

https://regex101.com/r/TimjdW/3

Anchor the start and end of the pattern at word boundaries with \b, then:

  • (?=\d*[a-z]) - Lookahead for an alphabetical character somewhere in the word
  • (?=[a-z]*\d) - Lookahead for a digit somewhere in the word
  • (?:[a-z]|(\d)(?!\w*\1))+ Repeatedly match either:
    • [a-z] - Any alphabetical character, or
    • (\d)(?!\w*\1) - A digit which does not occur again in the same word
like image 80
CertainPerformance Avatar answered Nov 14 '22 23:11

CertainPerformance