文章首发于:clawhub.club


java中通过split方法来分隔字符串,且支持正则表达式。空格在正则表达式中用\s标识,+号表示出现一次或者多次。

使用一个空格分隔字符串

1
2
3
4
5
6
7
8
9
10
11
12
//代码
String string = "Hi,hello world!";
String[] strArr = string.split("\\s");
System.out.println(strArr.length);
for (String str : strArr) {
System.out.println(str);
}
//结果
3
Hi,hello

world!

使用一个或多个空格分割字符串

1
2
3
4
5
6
7
8
9
10
11
//代码
String string = "Hi,hello world!";
String[] strArr = string.split("\\s+");
System.out.println(strArr.length);
for (String str : strArr) {
System.out.println(str);
}
//结果
2
Hi,hello
world!

以上代码区别就在于正则表达式+号的作用。

split方法

split(String regex, int limit)一般根据正则表达式分割字符串,limit限定分割后的子字符串个数,超过数量限制的情况下前limit-1个子字符串正常分割,最后一个子字符串包含剩下所有字符。重载方法split(String regex)将limit设置为0。

1
2
3
4
5
6
7
8
9
10
/**
* Splits this string around matches of the given regular expression
* This method works as if by invoking the two-argument {@link
* #split(String, int) split} method with the given expression and a limit
* argument of zero. Trailing empty strings are therefore not included in
* the resulting array.
*/
public String[] split(String regex) {
return split(regex, 0);
}

附正则表达式用法

字符类匹配

[…] 查找方括号之间的任何字符
[^…] 查找任何不在方括号之间的字符
[a-z] 查找任何从小写 a 到小写 z 的字符
[A-Z] 查找任何从大写 A 到大写 Z 的字符
[A-z] 查找任何从大写 A 到小写 z 的字符
. 查找单个字符,除了换行和行结束符
\w 查找单词字符,等价于[a-zA-Z0-9]
\W 查找非单词字符,等价于[^a-zA-Z0-9]
\s 查找空白字符
\S 查找非空白字符
\d 查找数字,等价于[0-9]
\D 查找非数字字符,等价于[^0-9]
\b 匹配单词边界
\r 查找回车符
\t 查找制表符
\0 查找 NULL 字符
\n 查找换行符

重复字符匹配

{n,m} 匹配前一项至少n次,但不能超过m次
{n,} 匹配前一项n次或更多次
{n} 匹配前一项n次
n? 匹配前一项0次或者1次,也就是说前一项是可选的,等价于{0,1}
n+ 匹配前一项1次或多次,等价于{1,}
n* 匹配前一项0次或多次,等价于{0,}
n$ 匹配任何结尾为 n 的字符串
^n 匹配任何开头为 n 的字符串
?=n 匹配任何其后紧接指定字符串 n 的字符串
?!n 匹配任何其后没有紧接指定字符串 n 的字符串

匹配特定数字

^[1-9]\d*$    匹配正整数

^-[1-9]\d*$   匹配负整数

^-?[0-9]\d*$   匹配整数

^[1-9]\d*|0$  匹配非负整数(正整数 + 0)

^-[1-9]\d*|0$   匹配非正整数(负整数 + 0)

^[1-9]\d*.\d*|0.\d*[1-9]\d*$  匹配正浮点数

^-([1-9]\d*.\d*|0.\d*[1-9]\d*)$ 匹配负浮点数

^-?([1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0)$  匹配浮点数

^[1-9]\d*.\d*|0.\d*[1-9]\d*|0?.0+|0$   匹配非负浮点数(正浮点数 + 0)

^(-([1-9]\d*.\d*|0.\d*[1-9]\d*))|0?.0+|0$  匹配非正浮点数(负浮点数 + 0)

匹配特定字符串

^[A-Za-z]+$ 匹配由26个英文字母组成的字符串

^[A-Z]+$  匹配由26个英文字母的大写组成的字符串

^[a-z]+$  匹配由26个英文字母的小写组成的字符串

^[A-Za-z0-9]+$  匹配由数字和26个英文字母组成的字符串

^\w+$  匹配由数字、26个英文字母或者下划线组成的字符串