I have these strings:
[?q]this is a test[?p]
And
[?q]this is a test<RANDOM_TAG>
I want to get all the text between [?q] and [?p] OR [?q] and <
Is it possible to do that in just one pattern?
I've done this so far:
[\\?q](.*?)(<)?
I have these strings:
[?q]this is a test[?p]
And
[?q]this is a test<RANDOM_TAG>
I want to get all the text between [?q] and [?p] OR [?q] and <
Is it possible to do that in just one pattern?
I've done this so far:
[\\?q](.*?)(<)?
On
First of all, to match brackets in regex, you have to escape them, or they'll be interpreted as a character class. Also, you can add an "or" in regex by using a '|' in the middle of a group.
So your regex would look like this:
\\[\\?q\\](.*?)(<|\\[\\?p\\])
Edit: The reason I'm using double slashes to escape is because that's what the question used, so I assume he's using Java.
You could use the following pattern:
Working example here on regex101.
How it works:
\[\?q\]checks for the literal sequence[?q](.*?)is the capturing group that gets any char sequence until it reaches either:\[\?p\](the literal sequence[?p]) or<To make the pattern look for either
[?p]or<, I used a non-capturing group,(?:...)containing the two patterns I can match, separated by a|, which means or.By the way, it seems that your pattern,
[\\?q](.*?)(<)?, doesn't escape the square brackets... you need to do so, using\;)Also, it seems that you're escaping the
\as well: are you using something like a Java String to create your pattern? If so, the actual JavaStringyou need to use is the following:Example usage in Java:
Output:
Hope this helps!