Papriker
Papriker

Reputation: 77

Regex to match character x times at the start of string but don't match at all if it's more than that

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?

Upvotes: 1

Views: 225

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

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.

Upvotes: 3

Related Questions