David Gard
David Gard

Reputation: 12077

Regular Expression to match part or all of a string

I create a regular expression on the fly based on the results of a variable. I've successfully tested most of the expression, but I'm struggling with the part that can vary in length.

How can I amend the regular expression (a_)?c(davison)\.nsf? so that any of the below strings would be classed as a match?

Essentially, to be considered a match, strings must meet the following criteria -

  1. "(a_)?" - May start with "a_" but doesn't have to
  2. "c" - Must contain the lowercase letter "c"
  3. "(davison)" - The bit I can't do - Must contain part or all of "davison", starting at the beginning (so "dav" is acceptable, but "son" is not)
  4. ".nsf" - Must finish with ".nsf"
  5. Length - Be no more than 12 characters in length, including the optional "_a" at the beginning of the string and the required ".nsf" at the end of the string.

Any hints and tips would be appreciated.

Upvotes: 2

Views: 100

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627410

To make each part of davison optional, use nested optional groups ((?:...)?), and to set the length restriction, you may use a negative lookahead anchored at the start to fail the match if 13 characters are found (thus, (?!.{13}) will allow strings of 12 and fewer characters in size):

^(?!.{13})(a_)?c(d(?:a(?:v(?:i(?:s(?:on?)?)?)?)?)?)\.nsf$

See the regex demo

Upvotes: 5

Related Questions