Adding an "or" to regex

89 views Asked by At

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](.*?)(<)?
3

There are 3 answers

4
ccjmne On BEST ANSWER

You could use the following pattern:

\[\?q\](.*?)(?:\[\?p\]|<)

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 Java String you need to use is the following:

"\\[\\?q\\](.*?)(?:\\[\\?p\\]|<)"

Example usage in Java:

public class Main {
    public static void main(final String[] args) {
        for (final String s : new String[] { "[?q]this is a test[?p]", "[?q]this is a test<RANDOM_TAG>" }) {
            System.out.println(s.replaceAll("(\\[\\?q\\])(.*?)(\\[\\?p\\]|<)", "$1AAA$3"));
        }
    }
}

Output:

[?q]AAA[?p]
[?q]AAA<RANDOM_TAG>

Hope this helps!

0
kabb 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.

1
e h On

Try: \[\?q\](.*?)(?:\[\?q\]|<)

From:

[?q]this is a test<RANDOM_TAG>

And:

[?q]this is a test[?q]RANDOM_TAG>

It matches: this is a test

See it in action.