java正则表达式(一)
在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串的需要。正则表达式就是用于描述这些规则的工具。换句话说,正则表达式就是记录文本规则的代码。
下面从最简单的正则表达式开始,循序渐进,达到逐渐了解正则表达式的目的。
一、通配符
在对网页内容、文本进行匹配时,往往我们需要能够一种通配符能够匹配所有字符,包括空格、Tab字符甚至换行符等。
在正则表达式中,通配符为“.” ,能够匹配任意字符,见代码示例:
public class RegExp {
private Pattern patt;
private Matcher matcher;
/**
* 通配符匹配: .符号在正则表达式中为通配符含义,匹配所有字符,包括空格、Tab字符甚至换行符
* @param regStr 匹配字符串
* @param regex 正则表达式
* @return
*/
public boolean wildcard(String regStr,String regex){
return this.commonRegExp(regStr, regex);
}
private boolean commonRegExp(String regStr,String regex){
boolean wildcard_Res=false;
patt=Pattern.compile(regex);
matcher=patt.matcher(regStr);
wildcard_Res= matcher.find();
return wildcard_Res;
}
}
public class TestRegExp {
public static void main(String[] args) {
RegExp re=new RegExp();
boolean wildcard_Res=false;
//通配符匹配
wildcard_Res=re.wildcard("tQn", "t.n");
System.out.println(wildcard_Res);
//wildcard_Res=true
}
浙公网安备 33010602011771号