1

Situation

I have a string that should start and end with %% and must not contain consecutive % signs.

My input strings are the followings: the first one is invalid, and the second is valid.

%%askdj%%kl%%
%%askdj%kasd%  lasdkl%%

I tried to validate with ^(%{2})([^\1]*?)\1$ and with ^(%{2})(.*(?!\1).*)\1$ but for the both cases I got the same result (it matches %%askdj%%kl%% as well, but should not).

I expected to exclude the first captured group by [^\1], but it did not work. Then I tried with negative lookahead, but it still did not work.

Questions

  • How do I match the valid text between %%?
  • How would you explain the not working behavior of the [^\1] pattern?
Artyom Vancyan
  • 2,348
  • 3
  • 10
  • 28
  • See https://regex101.com/r/GKHeQh/1, you need a tempered greedy token, inside character classes, backreferences are not parsed as such, and when using `.*(?!...).*`, these patterns match any text. – Wiktor Stribiżew Jun 04 '22 at 13:27
  • @WiktorStribiżew What if I also want to capture that text between `%%`? – Artyom Vancyan Jun 04 '22 at 13:31
  • 1
    Just [add the capturing group around that pattern](https://regex101.com/r/GKHeQh/2). – Wiktor Stribiżew Jun 04 '22 at 13:34
  • 1
    And `[^\1]` matches any char other than... the rest depends on the regex flavor. See an [example in Python](https://ideone.com/ERWteQ), `[^\1]` matches any char other than a char with octal ID 1, and a [POSIX ERE example](https://ideone.com/gNDU8o), where it matches any char other than a ``\`` and `1`. – Wiktor Stribiżew Jun 04 '22 at 13:42
  • @WiktorStribiżew, thank you very much. Now I got it. I voted to reopen the question as the linked one does not answer the question. And I will wait for your answer to accept it :) Good luck. – Artyom Vancyan Jun 04 '22 at 13:51
  • `(?:(?!\1).)*` [explained in the linked answer](https://stackoverflow.com/a/8057827/3832970) does answer this question. – Wiktor Stribiżew Jun 04 '22 at 13:53
  • Almost. [This](https://regex101.com/r/GKHeQh/2) was the answer to my question and the explanation of the `[^\1]` was very cool. Just I wanted to accept your answer. – Artyom Vancyan Jun 04 '22 at 13:57
  • To see the answer to the second question was more interesting to me. But you right [this](https://stackoverflow.com/questions/8055727/negating-a-backreference-in-regular-expressions/8057827#8057827) answers the first one. – Artyom Vancyan Jun 04 '22 at 14:00

0 Answers0