import java.util.regex.Pattern;
import java.util.regex.Matcher;
/*
字符串的边界匹配用的方法就是查找字符串是不是按照规定的模式开始和结束
^ 匹配字符串的开头位置,^\s* 表示字符串以零个或多个空白开头
$ 匹配字符串的结束位置
*/
public class StrBoundaryMatch{
public static void main(String[] args){
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
" " +
"xmlns:impl=\"http://tips.cf\" xmlns=\"http://tips.cf\""+
"xmlns:apachesoap=\"http://xml.apache.org/xml-soap\"";
//匹配 <?xml> 标签的正确性
//
Pattern p = Pattern.compile("");
Matcher m = p.matcher(str); //
System.out.println(p.pattern());
while (m.find()){
System.out.println(m.group());
}
//<?xml version="1.0" encoding="UTF-8" ?>
System.out.println();
String str2 = "This is bad, real bad!" +
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
" " +
"xmlns:impl=\"http://tips.cf\" xmlns=\"http://tips.cf\""+
"xmlns:apachesoap=\"http://xml.apache.org/xml-soap\"";
//这段作为 .xml 文件内容时候是有问题的,"This is bad, real bad!" 应该作为注释
//此时进行模式匹配的时候,希望做到的是,xml 文件以 <?xml ?> 开头,其他开头的都是错误的
// ^\s*
p = Pattern.compile("^\\s*");
m = p.matcher(str2);
System.out.println(m.find()); //false
//此时对 str 进行模式匹配
m = p.matcher(str);
while (m.find()){ //true
System.out.println(m.group());
}
//<?xml version="1.0" encoding="UTF-8" ?>
//已经匹配到了合法的内容
System.out.println();
//一个 xml 文件的结尾一定是