l
对于常用的字符组,正则表达式提供了相应的简记法,方便地表示它们
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
l
\d
=
[0-9]
l
\D
=
[^0-9]
l
\w
=
[0-9a-zA-Z_]
l
\w
=
[^0-9a-zA-Z_]
l
\s
匹配空白字符(回车、换行、制表、空格)
l
\S
匹配非空白字符
例子:
public
class
GeneralNumFive {
public
static
void
main(String[] args) {
String digitChar =
"\\d"
;
String noDigitChar =
"\\D"
;
String wordChar =
"\\w"
;
String noWordChar =
"\\W"
;
String
spaceChar
=
"\\s"
;
String noSapceChar =
"\\S"
;
String[] strs =
new
String[] {
"0"
,
"3"
,
"8"
,
"9"
,
"b"
,
"d"
,
"c"
,
" "
,
"\t"
,
"\n"
,
"\t"
};
for
(String string : strs) {
if
(
regexMatch
(string,digitChar)){
System.
out
.println(string +
"能够匹配正则:"
+ digitChar);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+ digitChar);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,noDigitChar)){
System.
out
.println(string +
"能够匹配正则:"
+ noDigitChar);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+ noDigitChar);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,wordChar)){
System.
out
.println(string +
"能够匹配正则:"
+ wordChar);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+ wordChar);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,noWordChar)){
System.
out
.println(string +
"能够匹配正则:"
+ noWordChar);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+ noWordChar);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,
spaceChar
)){
System.
out
.println(string +
"能够匹配正则:"
+
spaceChar
);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+
spaceChar
);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,noSapceChar)){
System.
out
.println(string +
"能够匹配正则:"
+ noSapceChar);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+ noSapceChar);
}
}
}
private
static
boolean
regexMatch(String s, String regex) {
return
s.matches(regex);
}
}
运行结果:
0能够匹配正则:\d
3能够匹配正则:\d
8能够匹配正则:\d
9能够匹配正则:\d
b不能够匹配正则:\d
d不能够匹配正则:\d
c不能够匹配正则:\d
不能够匹配正则:\d
不能够匹配正则:\d
不能够匹配正则:\d
不能够匹配正则:\d
0不能够匹配正则:\D
3不能够匹配正则:\D
8不能够匹配正则:\D
9不能够匹配正则:\D
b能够匹配正则:\D
d能够匹配正则:\D
c能够匹配正则:\D
能够匹配正则:\D
能够匹配正则:\D
能够匹配正则:\D
能够匹配正则:\D
0能够匹配正则:\w
3能够匹配正则:\w
8能够匹配正则:\w
9能够匹配正则:\w
b能够匹配正则:\w
d能够匹配正则:\w
c能够匹配正则:\w
不能够匹配正则:\w
不能够匹配正则:\w
不能够匹配正则:\w
不能够匹配正则:\w
0不能够匹配正则:\W
3不能够匹配正则:\W
8不能够匹配正则:\W
9不能够匹配正则:\W
b不能够匹配正则:\W
d不能够匹配正则:\W
c不能够匹配正则:\W
能够匹配正则:\W
能够匹配正则:\W
能够匹配正则:\W
能够匹配正则:\W
0不能够匹配正则:\s
3不能够匹配正则:\s
8不能够匹配正则:\s
9不能够匹配正则:\s
b不能够匹配正则:\s
d不能够匹配正则:\s
c不能够匹配正则:\s
能够匹配正则:\s
能够匹配正则:\s
能够匹配正则:\s
能够匹配正则:\s
0能够匹配正则:\S
3能够匹配正则:\S
8能够匹配正则:\S
9能够匹配正则:\S
b能够匹配正则:\S
d能够匹配正则:\S
c能够匹配正则:\S
不能够匹配正则:\S
不能够匹配正则:\S
不能够匹配正则:\S
不能够匹配正则:\S
注意:\\d
当字符串包含字符本身时,需要对其进行转
义
\
未完待续。。。