示例:
在源字符串“You may be out of my sight, but never out of my mind.”中查找“my”的个数。输出:匹配个数为2
三种方法:
1.通过String的indexOf方法
2. 通过正则表达式
3. 通过String的split方法
其中第一种方法只能用于精确匹配,第二三种则可以模糊匹配(方法3的参数为正则表达式)。例如:若将child改为“.my.”,第一种方法失效。
方法1:通过String的indexOf方法
public int indexOf(int ch, int fromIndex) :返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。如果不存在则返回 -1。
private void matchStringByIndexOf( String parent,String child )
{
int count = 0;
int index = 0;
while( ( index = parent.indexOf(child, index) ) != -1 )
{
index = index+child.length();
count++;
}
System.out.println( "匹配个数为"+count );
}
方法2:通过正则表达式
类 Pattern :正则表达式的编译表示形式。
指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式用于创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配。执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。
因此,典型的调用顺序是
Pattern p = Pattern.compile(“a*b”);
Matcher m = p.matcher(“aaaaab”);
boolean b = m.matches();
- 类 Matcher:通过调用模式的 matcher 方法从模式创建匹配器。创建匹配器后,可以使用它执行三种不同的匹配操作:
matches 方法尝试将整个输入序列与该模式匹配。
lookingAt 尝试将输入序列从头开始与该模式匹配。
find 方法扫描输入序列以查找与该模式匹配的下一个子序列
private void matchStringByRegularExpression( String parent,String child )
{
int count = 0;
Pattern p = Pattern.compile( child );
Matcher m = p.matcher(parent);
while( m.find() )
{
count++;
System.out.println( "匹配项" + count+":" + m.group() );
}
System.out.println( "匹配个数为"+count );
}
方法3:通过String的split方法
public String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。 该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,所得数组中不包括结尾空字符串。
private void matchStringBySplit( String parent,String child )
{
String[] array = parent.split(child);
System.out.println( "匹配个数为" + (array.length-1) );
}
完整代码:
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchString {
private void matchStringByIndexOf(String parent, String child) {
int count = 0;
int index = 0;
while ((index = parent.indexOf(child, index)) != -1) {
index = index + child.length();
count++;
}
System.out.println("匹配个数为" + count);
}
private void matchStringByRegularExpression(String parent, String child) {
int count = 0;
Pattern p = Pattern.compile(child);
Matcher m = p.matcher(parent);
while (m.find()) {
count++;
System.out.println("匹配项" + count + ":" + m.group());
}
System.out.println("匹配个数为" + count);
}
private void matchStringBySplit(String parent, String child) {
String[] array = parent.split(child);
System.out.println("匹配个数为" + (array.length - 1));
}
public static void main(String[] args) {
MatchString ms = new MatchString();
String parent = "You may be out of my sight, but never out of my mind.";
String child = "my";
System.out.println("------通过indexOf-------");
ms.matchStringByIndexOf(parent, child);
System.out.println("------通过正则表达式-------");
ms.matchStringByRegularExpression(parent, child);
System.out.println("------通过split方法-------");
ms.matchStringBySplit(parent, child);
String test = "abcdbdasda";
String[] as = test.split("a");
System.out.println(Arrays.toString(as));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)