How to match a line with exactly n occurrences with regex?

940 Views Asked by At

I am trying to match the lines containing exactly two semicolons (using Pythons re library):

 text;text;text;
 text;text;
 text;text;text;text;
 text;text;

However, I can't figure out how to not also include every line with more than 2 semicolons. So far I came up with this:

(?=.*[;]){2}$

This is how I understand the code:

(?=.*[;]) This part looks ahead and matches any and all characters as long as the are followed by one semicolon. With {2} this part is then matched exactly 2 times. After the second Semicolon the line ends ($).

Any pointers?

1

There are 1 best solutions below

2
On BEST ANSWER

So we want:

  • START OF LINE
  • 0 or more non-semicolons
  • semicolon
  • 0 or more non-semicolons
  • semicolon
  • EOL

Translating to regex we get:

^[^;]*;[^;]*;$

For the general case with N repetitions you can use

^([^;]*;){N}$