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?
This should match your requirement (I’ve tested it with you test cases):
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.