正则表达式基本内容
转义字符:比如要使用\d匹配一个数字、正则表达式中应当加上'\'反斜杠,即\\d
字符和字符类:(.)匹配任意字符、(\s)匹配空白字符等
定制字符类:[....]可以实现定制化字符类
位置标记:^ $ \b \B
多次、分组、捕获组、编号、交替、特殊选项、贪心程度、预处理模式和后处理模式等
附上Pat大师的 demo :)
package com.zhanxc.regex;
import java.util.*;
import java.util.regex.*;
public class Template
{
Properties values = new Properties();
Pattern templateComment =
Pattern.compile("(?si)<!--\\s*TEMPLATE:(\\w+).*?-->");
public void set( String name, String value ) {
values.setProperty( name, value );
}
public String fillIn( String text ) {
Matcher matcher = templateComment.matcher( text );
StringBuffer buffer = new StringBuffer();
while( matcher.find() ) {
String name = matcher.group(1);
String value = values.getProperty( name );
matcher.appendReplacement( buffer, value );
}
matcher.appendTail( buffer );
return buffer.toString();
}
public static void main( String [] args )
{
String templateText =
"<html><head>\n"+
"<body>\n"+
"This is some text.\n"+
"<!-- TEMPLATE:foo -->\n"+
"Some more text.\n"+
"\n"+
"<!--template:bar This is text -->\n"+
"More text.\n"+
"<!-- TEMPLATE:bar \n"+
"-->\n"+
"</body></html>\n";
Template template = new Template();
template.set( "foo", "FooTemplate");
template.set( "bar", "BarTemplate");
System.out.println( templateText );
System.out.println( template.fillIn(templateText) );
}
}
正则表达式实战
本文介绍正则表达式的使用方法,包括转义字符、字符类、位置标记等基础概念,并通过一个Java实例演示如何利用正则表达式进行文本匹配与替换。
1275

被折叠的 条评论
为什么被折叠?



