参考:http://www.ibm.com/developerworks/cn/java/j-perry-regular-expressions/index.html
Regular Expressions API 有 3 个核心类:
- Pattern 描述了一种字符串模式。
- Matcher 测试一个字符串,查看它是否与该模式匹配。
- PatternSyntaxException 告诉您,您尝试定义的模式的某个方面无法被接受。
正则表达式模式语法
Matcher 的常用方法
- 模式匹配
Pattern pattern = Pattern.compile("[Aa].*string");
Matcher matcher = pattern.matcher("A string");
boolean didMatch = matcher.matches();
int patternStartIndex = matcher.start();
int patternEndIndex = matcher.end();
matches() 告诉您整个输入序列是否与该模式准确匹配。
start() 告诉您匹配的字符串在输入字符串中的起点的索引值。
end() 告诉您匹配的字符串在输入字符串中的起点的索引值加 1 的结果
lookingAt() 与 matches() 的对比分析
如果您的字符串中包含的元素比您搜索的模式中字符数要多,可以使用 lookingAt() 代替 matches()。lookingAt() 方法搜索与一种指定模式匹配的子字符串。例如,考虑下面这个字符串:
a string with more than just the pattern.
如果在此字符串中搜索 a.*string,而且您使用了 lookingAt(),则会获得一个匹配结果。但是,如果您使用 matches(),则会返回 false,因为字符串中包含比模式中更多的内容。
- 替换字符串
replaceAll() 将所有匹配值替换为一个指定的字符串。
replaceFirst() 仅将第一个匹配值替换为一个指定的字符串。
String input = "Here is a WikiWord followed by AnotherWikiWord, then SomeWikiWord.";
Pattern pattern = Pattern.compile("[A-Z][a-z]*([A-Z][a-z]*)+");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("replacement");
Before: Here is WikiWord followed by AnotherWikiWord, then SomeWikiWord.
After: Here is replacement followed by replacement, then replacement.
- 匹配和操作分组
String input = "Here is a WikiWord followed by AnotherWikiWord, then SomeWikiWord.";
Pattern pattern = Pattern.compile("[A-Z][a-z]*([A-Z][a-z]*)+");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("blah$0blah");
通过在替换字符串中包含 $0
来引用完整匹配结果。$ int
格式的替换字符串的任何部分引用该整数所标识的分组(所以 $1
引用分组 1,依此类推)。换句话说,$0
等效于 matcher.group(0);。
可以使用其他一些方法达到同样的替换目的。无需调用 replaceAll():
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, "blah$0blah");
}
matcher.appendTail(buffer);
两种方法结果相同:
Before: Here is a WikiWord followed by AnotherWikiWord, then SomeWikiWord.
After: Here is a blahWikiWordblah followed by blahAnotherWikiWordblah,then blahSomeWikiWordblah.
常用正则式
- wiki单词(由两个或多个单词组合在一起,每个单词的首字母大写,如FileName): [A-Z][a-z]([A-Z][a-z])+
可能还是对正则表达式的符号掌握不够熟练,每次遇到都要现查表,即使是自己写的时候,虽然一边看表一边也能写出来,但是很浪费时间,总是还是一个熟练使用的过程吧。网上有很多整理好的常用的正则表达式,可作为参考,如http://www.2cto.com/kf/201405/300289.html(并未逐条进行验证)