javaregexparsingregex-group

How to make regex pattern for some scenarios


Am doing WordXml parsar using JAVA.

And now i want to check (F(1) = 44) this type of pattern will be occured or not in a paragraph.

Note: Inside of open close will have must integer value.

Folloing pattern i will need to check.

(text text (text) text)
(F(1) = 44)
(text text [text] text)
[text text (text) text]

But, Clearly don't know how to make regex pattern for above the senarios.

So, Please suggest me. And anybody pls let me know.


Solution

  • You can use this regex \([a-zA-Z]+\(\d+\)\s*=\s*\d+\), which mean

    with Pattern like this :

    String[] texts = new String[]{"(text text (text) text)",
        "(F(1) = 44)",
        "(text text [text] text)",
        "[text text (text) text]"};
    String regex = "\\([a-zA-Z]*\\(\\d+\\)\\s*=\\s*\\d+\\)";
    
    for (String s : texts) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            System.out.println("There are match " + matcher.group());
        } else {
            System.out.println("No match occurred");
        }
    }
    

    Output

    No match occurred
    There are match (F(1) = 44)
    No match occurred
    No match occurred
    

    regex demo