my regex does not pick the closest [A] What can be a solution for this case?
Input:
[A]xxx[A]yyyy[B]
Regex:
\[A\](?!\[A\])(.*?)\[B\]
Match:
[A]xxx[A]yyyy[B]
Match I need:
[A]yyyy[B]
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are actually close. The only issue is that the lookahead does not look all the way through the string by itself. It will only look at the current position. You can help it out though:
If your input might contain multiple pairs of
[A]...[B](consecutively) and you want to match all of them, you can either go with Bohemian’s answer, or use the more general approach (which will work for more complex exclusion patterns) and check the lookahead at every position:This will only consume another character (
.) if that character does not mark the beginning of an[A]. The+after the*makes the latter possessive, which is just an optimization applicable in this case.