"contains at least one of the following letters" type regex issue

Viewed 81

I'm having a bit of a issue getting an "at least one of certain characters" type regex working.

There are obviously similar questions to my problem but the solutions I am trying are not resolving an incorrect match.

Basically, the regex should match:

(starts with a forward slash) (has a-z letters but must contain at least an "a", "b" or "d" - this part should be 3 to 4 characters long) (ends in a single digit followed by a slash, the URL need not finish here - can be longer)

I've got the following but it doesn't work exactly as expected:

\/(?=.*[a|b|d])[a-z]{3,4}[\d]\/

The above expression incorrectly matches (/ccc1/) of the following expressions (see example at https://regex101.com/r/6ET43K/4/ ):

http://example.com/folder/aaaa/ - no match (no digit at end)

http://example.com/folder/bbb1/ - match (has at least one "b", and digit)

http://example.com/folder/ccc1/ - no match (has neither "a", "b" or "d")

http://example.com/folder/yyd3/ - match (has at least one "d", and digit)

http://example.com/folder/yydd3/ - match (has at least one "d", and digit)

http://example.com/folder/yyddd3/ - no match (too long)

I'd be very grateful for any pointers as to what I'm doing wrong here. Thanks!

2 Answers

You might use

^.*\/(?=[a-z]{3,4}\d\/)[a-z]*[abd][a-z]*\d\/

Explanation

  • ^ Start of string
  • .*\/ Match until the last /
  • (?= Positive lookahead
    • [a-z]{3,4}\d\/ Assert 3 or 4 times a char a-z followed by 1 digit and /
  • ) Close lookahead
  • [a-z]*[abd][a-z]* match at least a single a b or d between optional chars a-z
  • \d\/ Match 1 digit and /

Regex demo

Alternatively, maybe the following will do:

^.*\/(?=[a-z]*[abd])[a-z]{3,4}\d\/

See the online demo


  • ^ - Start string anchor.
  • .*\/ - Match greedy untill the last forward slash.
  • (?=[a-z]*[abd]) - Positive lookahead with a to match as many alpha chars untill either a, b or d.
  • [a-z]{3,4}\d\/ - Three to four alpha chars, a digit and a literal forward slash.
Related