Suraj
Suraj

Reputation: 36547

regex to start and end with character set, but with different character set in-between

I'm trying to create a Regex that:

Example

Here's what I have so far:

^[a-c|e-g][a-g]{0,8}[a-c|e-g]{0,1}$

This seems to work, EXCEPT if d is the last character and total character count < MAX_CHARS

Is there a way to fix this up?

Upvotes: 2

Views: 48

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You may use

^(?!.{11})(?=.*[a-ce-g]$)[a-ce-g][a-g]{0,9}$

See the regex demo.

Details

  • ^ - start of string
  • (?!.{11}) - up to 10 chars allowed
  • (?=.*[a-ce-g]$) - after 0 or more chars, the last one should be from FIRST SET
  • [a-ce-g] - a letter from the FIRST SET
  • [a-g]{0,9} - zero to nine chars in the SECOND SET
  • $ - end of string.

Note that | inside character classes match literal pipe chars, you need to remove it from your pattern.

The (?!.{11}) negative lookahead is executed once at the start of the string and fails the match if there are any 11 chars (other than newline) in the string. You may also use (?=.{0,10}$), it will require 0 to 10 chars in the string only.

Upvotes: 2

Related Questions