切割字符串
分隔字符串是java中常用的操作,String的split方法可以進行字符串切割操作,然而日常使用卻僅僅限於str.split("-"),其中“-”為分隔符。其實split方法很強大,有更優雅的方式去切割字符串
使用方法
public String[] split(String regex)
其中regex代表正則表達式分隔符,我們平時使用單個字符作為分隔符,其實可以看做是特殊的正則表達式,特殊之處在於這種表達式在匹配自身,如"-"只匹配"-",示例如下:
String string = "86-15003455666";
String[] parts = string.split("-");
String part1 = parts[0]; // 86
String part2 = parts[1]; // 15003455666
split還有另一種用法
public String[] split(String regex,int limit)
regex指的是正則表達式分隔符,limit值的是分隔的份數,如:
String string = "004-556-42";
String[] parts = string.split("-", 2); // 限定分割兩份
String part1 = parts[0]; // 004
String part2 = parts[1]; // 556-42
在某些場景下,我們可能想要在結果中保留分隔符,這也是可以做到的,設置分隔符與分割后的左側結果相連
String string = "86-15003455666";
String[] parts = string.split("(?<=-)");
String part1 = parts[0]; // 86-
String part2 = parts[1]; // 15003455666
設置分隔符與分割后右側的結果相連:
String string = "86-15003455666";
String[] parts = string.split("(?=-)");
String part1 = parts[0]; // 86-
String part2 = parts[1]; // 15003455666
所以說要妙用正則表達式,代碼示例:
//\d代表數字,+代表出現一次或多次。所以(\\d+)-(\\d+)匹配用"-"相連的兩個數字串
// Pattern 對象是正則表達式的編譯表示
private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
public static void checkString(String s)
{
// Matcher對象對輸入字符串進行解釋和匹配操作
Matcher m = twopart.matcher(s);
if (m.matches()) {
//m.group(1) 和 m.group(2) 存儲分割后的子串
System.out.println(s + " matches; first part is " + m.group(1) +
", second part is " + m.group(2) + ".");
} else {
System.out.println(s + " does not match.");
}
}
public static void main(String[] args) {
checkString("123-4567"); // 匹配
checkString("s-tar"); // 字母序列,不匹配
checkString("123-"); // "-"右側的數字串為空,不匹配
checkString("-4567"); // "-"左側的數字串為空,不匹配
checkString("123-4567-890"); // 存在兩個"-",不匹配
}
運行結果:
123-4567 matches; first part is 123, second part is 4567.
s-tar does not match.
123- does not match.
-4567 does not match.
123-4567-890 does not match.