在Java中,字符串的匹配可以使用下面两种方法:
1、使用正则表达式判断字符串匹配
2、使用Pattern类和Matcher类判断字符串匹配
正则表达式的字符串匹配:
正则表达式:定义一组字符串的一系列字符和符号,它由常量字符和特殊符号构成。
下面是正则表达式的一些预定义字符类,实际上是一些转义字符序列:
1、\d 代表任何数字
2、\D 代表任何非数字字符
3、\w 代表任何单字字符(如:字母、数字、下划线等等)
4、\W 代表任何非单字字符
5、\s 代表任何空白字符
6、\S 代表任何非空白字符
为了匹配一组没有预定义字符类的字符,可以用[]指明
正则表达式常用*、+、?等来表示匹配字符的个数
1、* 表示匹配字符个数为0个或多个
2、+ 表示匹配字符个数为1个或多个
3、? 表示匹配字符个数为0个或1个
4、{n} 表示匹配字符的个数正好为n个
5、{n,} 表示匹配字符个数至少为n个
6、{n,m} 表示匹配字符个数至少为n个,最多为m个
上面简要的介绍了正则表达式的语法,下面通过实例来说明具体用法:
定义如下的正则表达式regex:
String regex="[0]\\d{2,3}[-][1-9]\\d{6,7}"
含义说明如下:
1、[0]表示字符串中第一个字符必须是0
2、\\d{2,3}数字0后面最少2个数字、最多3个数字
3、[-]表明这里必须是连字符-
4、[1-9]表示只能是数字1~9
5、 \\d{6,7}表示这里最少6个数字,最多7个数字
package day_21;
public class day21 {
public static final int MAX_LENGTH = 10;
int length;
char[] data;
public day21() {
length = 0;
data = new char[MAX_LENGTH];
}// Of the first constructor
public day21(String paraString) {
data = new char[MAX_LENGTH];
length = paraString.length();
// Copy data.
for (int i = 0; i < length; i++) {
data[i] = paraString.charAt(i);
} // Of for i
}// Of the second constructor
public String toString() {
String resultString = "";
for (int i = 0; i < length; i++) {
resultString += data[i];
} // Of for i
return resultString;
}// Of toString
public int locate(day21 paraMyString) {
boolean tempMatch = false;
for (int i = 0; i < length - paraMyString.length + 1; i++) {
// Initialize.
tempMatch = true;
for (int j = 0; j < paraMyString.length; j++) {
if (data[i + j] != paraMyString.data[j]) {
tempMatch = false;
break;
} // Of if
} // Of for j
if (tempMatch) {
return i;
} // Of if
} // Of for i
return -1;
}// Of locate
public day21 substring(int paraStartPosition, int paraLength) {
if (paraStartPosition + paraLength > length) {
System.out.println("The bound is exceeded.");
return null;
} // Of if
day21 resultMyString = new day21();
resultMyString.length = paraLength;
for (int i = 0; i < paraLength; i++) {
resultMyString.data[i] = data[paraStartPosition + i];
} // Of for i
return resultMyString;
}// Of substring
public static void main(String args[]) {
day21 tempFirstString = new day21("I like ik.");
day21 tempSecondString = new day21("ik");
int tempPosition = tempFirstString.locate(tempSecondString);
System.out.println("The position of \"" + tempSecondString + "\" in \"" + tempFirstString
+ "\" is: " + tempPosition);
day21 tempThirdString = new day21("ki");
tempPosition = tempFirstString.locate(tempThirdString);
System.out.println("The position of \"" + tempThirdString + "\" in \"" + tempFirstString
+ "\" is: " + tempPosition);
tempThirdString = tempFirstString.substring(1, 2);
System.out.println("The substring is: \"" + tempThirdString + "\"");
tempThirdString = tempFirstString.substring(5, 5);
System.out.println("The substring is: \"" + tempThirdString + "\"");
tempThirdString = tempFirstString.substring(5, 6);
System.out.println("The substring is: \"" + tempThirdString + "\"");
}// Of main
}// Of class MyString