Java - 正则表达式常用操作

验证

简单验证

String regex = "\\d{4}-\\d{2}-\\d{2}";
String input = "2016-01-01";
assertTrue(input.matches(regex));
assertTrue(Pattern.matches(regex, input));

 

提取

String regex = "\\d{4}-\\d{2}-\\d{2}";
String input = "2016-01-01, 2016-02-02. [2016-03-03]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
    System.out.println(matcher.group());
}

 

替换

简单替换

String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
String replacement = "$2/$3/$1";
String input = "2016-01-15, 2016-02-15.";
String actual = input.replaceAll(regex, replacement);
String expected = "01/15/2016, 02/15/2016.";
assertEquals(expected, actual);

使用 Pattern 对象,方便反复使用

String regex = "(\\d{4})-(\\d{2})-(\\d{2})";
String replacement = "$2/$3/$1";
String input = "2016-01-15, 2016-02-15.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String actual = matcher.replaceAll(replacement);
String expected = "01/15/2016, 02/15/2016.";
assertEquals(expected, actual);

 

切分

简单切分

String regex = "\\s+";
String input = "a  b\tc";
String[] actuals = input.split(regex);
String[] expecteds = new String[] {"a", "b", "c"};
assertArrayEquals(expecteds, actuals);

使用 Pattern 对象,方便反复使用

String regex = "\\s+";
String input = "a  b\tc";
Pattern pattern = Pattern.compile(regex);
String[] actuals = pattern.split(input);
String[] expecteds = new String[] {"a", "b", "c"};
assertArrayEquals(expecteds, actuals);

 

posted on 2016-05-26 14:46  huey2672  阅读(258)  评论(0编辑  收藏  举报