1 String类的自建功能
2 利用Pattern和Matcher的操作字符串
下面是具体代码
1String类的自建功能
/***
* 字符串自带表达式处理
*/
public static void stringRegex(){
System.out.println("55".matches("\\d+"));//String自身就可以对正则表达式格式做简单检查
System.out.println("-90".matches("(\\+|-)?\\d+"));
System.out.println("-90.6".matches("(\\+|-)?\\d+"));
}
说明:这里面通过字符串自身功能进行匹配,查找字符串是否符是数字。
表达式"\\d+"表示正整数,表达式(\\+|-)?\\d+ 表示正负整数.
字符串中 split和replace中也使用正则表达式
2利用Pattern和Matcher的操作字符串
/**从字符串中检查符合相应规范的字符串*/
publicstaticvoidfindFromSource(){
Stringsource="<?xmlversion=\"1.0\"encoding=\"UTF-8\"?>"+
"<plistversion=\"1.0\">"+
"<dict>"+
"<key>MessageType</key>"+
"<string>TokenMessage</string>"+
"<key>PushMagic</key>"+
"<string>1234556</string>"+
"<key>Token</key>"+
"<data>"+
"tokendata"+
"</data>"+
"<key>Topic</key>"+
"<string>com.apple.apn</string>"+
"<key>UDID</key>"+
"<string>1234567890</string>"+
"<key>UnlockToken</key>"+
"<data>"+
"thisisunlockToken字符串"+
"</data>"+
"</dict>"+
"</plist>";
Patternpattern=Pattern.compile("<key>Topic</key>\\s*<string>\\s*([^\\s]*)\\s*</string>");
Matchermatcher=pattern.matcher(source);
if(matcher.find()){
System.out.println(matcher.group(1));////组1,就是()里面的内容,也就是Topic的值
System.out.println(matcher.group());
}
// Stringwords="thisisagood";//将返回true
Stringwords="thisisagood!";//将返回false
Patternpattern2=Pattern.compile("[\\w|\\s]*");//匹配字符和空格
Matchermatcher2=pattern2.matcher(words);
System.out.println(matcher2.matches());//是从头开始匹配,完全匹配才返回true
}
publicstaticvoidfindFromSource(){
Stringsource="<?xmlversion=\"1.0\"encoding=\"UTF-8\"?>"+
"<plistversion=\"1.0\">"+
"<dict>"+
"<key>MessageType</key>"+
"<string>TokenMessage</string>"+
"<key>PushMagic</key>"+
"<string>1234556</string>"+
"<key>Token</key>"+
"<data>"+
"tokendata"+
"</data>"+
"<key>Topic</key>"+
"<string>com.apple.apn</string>"+
"<key>UDID</key>"+
"<string>1234567890</string>"+
"<key>UnlockToken</key>"+
"<data>"+
"thisisunlockToken字符串"+
"</data>"+
"</dict>"+
"</plist>";
Patternpattern=Pattern.compile("<key>Topic</key>\\s*<string>\\s*([^\\s]*)\\s*</string>");
Matchermatcher=pattern.matcher(source);
if(matcher.find()){
System.out.println(matcher.group(1));////组1,就是()里面的内容,也就是Topic的值
System.out.println(matcher.group());
}
// Stringwords="thisisagood";//将返回true
Stringwords="thisisagood!";//将返回false
Patternpattern2=Pattern.compile("[\\w|\\s]*");//匹配字符和空格
Matchermatcher2=pattern2.matcher(words);
System.out.println(matcher2.matches());//是从头开始匹配,完全匹配才返回true
}
其中matcher中有组的概念,组就是用()括起来的内容 ,例如:A(B(C))D 组0 就是ABCD ,组1是BC,组2是C
参考资料:Java编程思想。