Java Pattern Match
Use escape when there are parenthesis in regex.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void testRegexLongMatcher() {
String user_agent = "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0";
boolean expResult = false;
boolean result = Pattern.compile("((X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0|(X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/39.0)", Pattern.CASE_INSENSITIVE).matcher(user_agent).find();
assertEquals(expResult, result);
}
@Test
public void testRegexLongMatcherWithParenthesisEscape() {
String user_agent = "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0";
boolean expResult = true;
boolean result = Pattern.compile("(\\(X11; Linux i686; rv:38.0\\) Gecko/20100101 Firefox/38.0|\\(X11; Linux i686; rv:38.0\\) Gecko/20100101 Firefox/39.0)", Pattern.CASE_INSENSITIVE).matcher(user_agent).find();
assertEquals(expResult, result);
}
This post is licensed under CC BY 4.0 by the author.