Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading