cc在哪
2016-10-24 12:54
^和\A的区别
$和\Z的区别
public static void main(String[] args) {
String matcherStr = "This is the first Java";
matcherStr += "\nAnd";
matcherStr += "\nThis is the second Python";
Matcher matcher = Pattern.compile("Java$", Pattern.MULTILINE).matcher(matcherStr);
int i=0;
while(matcher.find()){
i++;
}
System.out.println(i);
}There is one match (i=1) for Java in the first line. This is mutiline, so the whole matcherStr is something like:
This is the first Java
And
This is the second Python
public static void main(String[] args) {
String matcherStr = "This is the first Java";
matcherStr += "\nAnd";
matcherStr += "\nThis is the second Java";
Matcher matcher = Pattern.compile("Java$", Pattern.MULTILINE).matcher(matcherStr);
int i=0;
while(matcher.find()){
i++;
}
System.out.println(i);
}There are two matchs (i=2) for Java in the first line. This is mutiline, so the whole matcherStr is something like:
This is the first Java
And
This is the second Java
public static void main(String[] args) {
String matcherStr = "This is the first Java";
matcherStr += "\nAnd";
matcherStr += "\nThis is the second Python";
Matcher matcher = Pattern.compile("Java$").matcher(matcherStr);
int i=0;
while(matcher.find()){
i++;
}
System.out.println(i);
}There is no match (i=0) for Java. This is not mutiline, so the whole matcherStr is something like:
This is the first Java\nAnd\nThis is the second Python
public static void main(String[] args) {
String matcherStr = "This is the first Java";
matcherStr += "\nAnd";
matcherStr += "\nThis is the second Java";
Matcher matcher = Pattern.compile("Java\\Z", Pattern.MULTILINE).matcher(matcherStr);
int i=0;
while(matcher.find()){
i++;
}
System.out.println(i);
}There is one match (i=1) for Java with multiline. The same as without multiline.
In this case: If Pattern.compile("Java$", Pattern.MULTILINE), there are two matches.
public static void main(String[] args) {
String matcherStr = "This is the first Java";
matcherStr += "\nAnd";
matcherStr += "\nThis is the second Java";
Matcher matcher = Pattern.compile("Java\\Z").matcher(matcherStr);
int i=0;
while(matcher.find()){
i++;
}
System.out.println(i);
}There is one match (i=1) for Java without multiline.
^
指定匹配必须出现在字符串的开头或行的开头。
\A
指定匹配必须出现在字符串的开头(忽略 Multiline 选项)。
$
指定匹配必须出现在以下位置:字符串结尾、字符串结尾的 \n 之前或行的结尾。
\Z
指定匹配必须出现在字符串的结尾或字符串结尾的 \n 之前(忽略 Multiline 选项)。
python正则表达式
80572 学习 · 176 问题
相似问题