Java regex problem with two or more signs

Viewed 74

I want to write a regex pattern which find strings containts only: p, q, r, ^, v and ~ signs, but also implication and equivalence, represented by two (=>) or three (<=>) signs. How can I do that?

For example that pattern:

Pattern pattern = Pattern.compile("[(=>)(<=>)]*");

Matches strings that contains: (, =, >, <, ) signs, whereas I want to write a pattern which contains only *=>* and *<=>*.

2 Answers

You can change your pattern to be like this:

public static void main(String[] args) {
    Pattern pattern = Pattern.compile("(p|q|r|v|\\^|~|=>|<=>)");
    Matcher matcher = pattern.matcher(yourString);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
}

The issue you had is that [...] is a character set, meaning that it matches against the individual characters you have inside the braces, rather than the full string.

Your current pattern is a character class and could also be written as [()<>=]*

You can update your pattern by adding p, q, r, ^, v and ~ signs to the character class instead [pqrv^~].

To match either => or <=> you can make < optional using a question mark.

The full pattern could be written using an alternation an a non capturing group:

(?:[pqrv^~]|<?=>)

Regex demo

The code could look like

Pattern pattern = Pattern.compile("(?:[pqrv^~]|<?=>)");
Related