2
votes

I'm taking a beating to build a regular expression.

Rules for matching:

  • Must contain the EN string
  • The String must be between parentheses
  • At the starting parentheses, there must be a !
  • The string can be anywhere inside the perentheses
  • Should the EN string exist outside parentheses, it mustn't match

The string to match the RegEx can have the following formats, with the expected respective answers:

public void testRegexToMatchContextToIgnoreFromString() {
    String regex = "\\([^\\(].?[EN+].?\\)";
    assertTrue("!(EN)CLIENT".matches(regex));
    assertTrue("!(EN,PR)CLIENT".matches(regex));
    assertTrue("!(PR,EN)CLIENT".matches(regex));

    assertFalse("!(PR)CLIENT".matches(regex));
    assertFalse("!(CO,PR)CLIENT".matches(regex));
}

I tried various ways, but I understand little on RegEx, so I ended up going in circles not getting anywhere. Can someone help me?

2
You said you want to return true when your string contains EN outside parenthesis as per last requirement, but in your example you are returning true for them. What do you exactly want it to return? - Rohit Jain

2 Answers

2
votes

This should match your requirement (I've tested it with you test cases):

String regex = ".*!\\(.*EN.*\\).*";

Explanation: First zero or more of any character (.*). Then '!(', then zero or more of any character, then 'EN', then zero or more of any character, then the closing parenthesis and again zero or more of any character.

0
votes

Here's your regex DEMO

!\([^\(\)]*EN[^\(\)]*\)

NOTE: is not scaped for java.