Rock
Rock

Reputation: 23

how to write a regex that has substring match and exclude another substring

I want to write a regex to evaluate 12 character strings, a sample string is a02016ab-B30, I want to find all strings that have 4 to 6 character as 016 and 10 to 11 character not as B3.

.{3}(061).{3}(?!B3) doesn't exclude string with more than 12 characters? how can I refine it?

Upvotes: 2

Views: 288

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

You may use

^.{3}061.{3}(?!B3).{3}$

Or, if you have 016 after the first three chars:

^.{3}016.{3}(?!B3).{3}$

See the regex demo.

Details

  • ^ - start of string
  • .{3} - any three chars other than line break chars
  • 061 - a substring
  • .{3} - any three chars other than line break chars
  • (?!B3) - B3 substring is not allowed at the current location
  • .{3} - any three chars other than line break chars
  • $ - end of string.

Upvotes: 1

Related Questions