I am using a regex pattern to find instances of [code][/code] BB tags. (This is in PHP with pearl-type regex using preg_match / preg_relace / etc)
'~\[code\](.*?)\[\/code\]~is'
Well, my question is how can I make it so somebody could type something like:
[code][code]code here[/code][/code]
The purpose of typing this would be to demonstrate to a newbie how to place their code into [code][/code] tags.
Currently if I type that, the regex will stop at the 1st instance of “[/code]” and not keep looking ahead to see the 2nd instance of “[code]”
I can’t post images since I’m a new user, but here is a screenshot of the output:
https://i.stack.imgur.com/7gS6x.png
I know there is a term in regex called “positive look ahead” and “negative look ahead”, but I’m not quite sure what they mean, or if they are relevant to my situation. Could someone please give me a hand? Thank you.
EDIT: I’m sorry but I don’t seem to have enough rep to +1 anything. I really appreciate your help, and it was so fast.
If you want to cover also the case that there can be more code between the two closing tags you can try this one
See it here on Regexr
The first part
\[code\].*?\[\/code\]is matching from the first opening tag to the first closing tag.Then comes the tricky part that is now optional.
(?:(?:(?!\[code\]).)*\[\/code\])?is matching characters, if the there is not an opening tag following, till the last closing tag found.