public int start() 这个方法返回了,Matcher所匹配的字符串在整个字符串的的开始下标:
public class MatcherStartExample{
public static void main(String args[]){
test();
}
public static void test(){ //create a Matcher and use the Matcher.start() method
String candidateString = "My name is Bond. James Bond.";
String matchHelper[] =
{" ^"," ^"};
Pattern p = Pattern.compile("Bond");
Matcher matcher = p.matcher(candidateString);
//Find the starting point of the first 'Bond'
matcher.find();
int startIndex = matcher.start();
System.out.println(candidateString);
System.out.println(matchHelper[0] + startIndex);
//Find the starting point of the second 'Bond'
matcher.find();
int nextIndex = matcher.start();
System.out.println(candidateString);
System.out.println(matchHelper[1] + nextIndex);
}输出结果: My name is Bond. James Bond. ^11 My name is Bond. James Bond. ^23
我自己改了这个例子import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPatternAndMatcher3 {
public static void test(){
String candidateString = "My name is Bond. James Bond.";
String matchHelper[] = {" ^", +
" ^"};
Pattern p = Pattern.compile("Bond");
Matcher matcher = p.matcher(candidateString);
matcher.find();
int startIndex = matcher.start();
System.out.println(candidateString);
System.out.println(matchHelper[0] + startIndex);
char[] al = candidateString.toCharArray();
System.out.println("al[startIndex] : " + al[startIndex]);
matcher.find();
int nextIndex = matcher.start();
System.out.println(candidateString);
System.out.println(matchHelper[1] + nextIndex);
char[] al2 = candidateString.toCharArray();
System.out.println("al2[startIndex] : " + al2[startIndex]);
}
public static void main(String[] args) {
test();
}
}
</pre><pre class="java" name="code" style="color: rgb(102, 102, 102); background-color: rgb(255, 255, 255);">import java.util.regex.*;
public class MatcherGroupExample{
public static void main(String args[]){
test();
}
public static void test(){
//create a Pattern
Pattern p = Pattern.compile("Bond");
//create a Matcher and use the Matcher.group() method
String candidateString = "My name is Bond. James Bond.";
Matcher matcher = p.matcher(candidateString);
//extract the group
matcher.find();
System.out.println(matcher.group());
}
}
public int groupCount()
这个方法返回了,正则表达式的匹配的组数。 妈的这个微博排版这么费事!!!
原博客地址http://www.java3z.com/cwbwebhome/article/article8/81313.html?id=3138
Java正则表达式实战
本文通过具体示例介绍了Java中使用正则表达式的Matcher类的方法,包括如何获取匹配字符串的开始位置及匹配组数。并通过两个实例展示了Matcher类中start()与groupCount()方法的应用。
1万+

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



