Home > Software design >  Regex to match character x times at the start of string but don't match at all if it's mor
Regex to match character x times at the start of string but don't match at all if it's mor

Time:02-08

I'm currently facing the problem that I want to match a character (%) x times but not more than that at the start of a line. My initial thought was to do this:

^%{1,6}

but this matches %%%%%%%

Is there a way to not make it match at all if the maximum is reached?

CodePudding user response:

You can use

^%{1,6}(?!%)

See the .NET regex demo.

Details:

  • ^ - start of string
  • %{1,6} - one to six occurrences of a % char
  • (?!%) - a negative lookahead that fails the match if there is a % char immediately on the right.
  •  Tags:  
  • Related