public
class
GeneralNumSix {
public
static
void
main(String[] args) {
String
mixedRegex
=
"[\\da-f]"
;
String[] strs =
new
String[] {
"0"
,
"1"
,
"2"
,
"3"
,
"4"
,
"9"
,
"a"
,
"e"
,
"f"
,
"g"
,
"z"
};
for
(String string : strs) {
if
(
regexMatch
(string,
mixedRegex
)){
System.
out
.println(string +
"能够匹配正则:"
+
mixedRegex
);
}
else
{
System.
out
.println(string +
"不能够匹配正则:"
+
mixedRegex
);
}
}
}
private
static
boolean
regexMatch(String s, String regex) {
return
s.matches(regex);
}
}
运行结果:
0能够匹配正则:[\da-f]
1能够匹配正则:[\da-f]
2能够匹配正则:[\da-f]
3能够匹配正则:[\da-f]
4能够匹配正则:[\da-f]
9能够匹配正则:[\da-f]
a能够匹配正则:[\da-f]
e能够匹配正则:[\da-f]
f能够匹配正则:[\da-f]
g不能够匹配正则:[\da-f]
z不能够匹配正则:[\da-f]
注意:
能够匹配数字字符,和小写a-f之间
除此之外,都不能匹配。
特殊的简记法:点号
-
点号 . 是一个特殊的字符组简记法,它可以匹配几乎所有字符
-
\. 匹配点号本身
-
在字符组内部,[.]也只能匹配点号本身
-
注意:点号不能匹配换行符
例子:
public
class
GeneralNumSeven {
public
static
void
main(String[] args) {
String[] strs =
new
String[] {
"0"
,
"1"
,
"2"
,
"$"
,
"{"
,
"}"
,
"."
,
"["
,
"]"
,
"\n"
};
String normalDot =
"."
;
String escapedDot =
"\\."
;
String characterClassDot =
"[.]"
;
for
(String string : strs) {
if
(
regexMatch
(string,normalDot)){
System.
out
.
println
(string +
"能够匹配正则:"
+ normalDot);
}
else
{
System.
out
.
println
(string +
"不能够匹配正则:"
+ normalDot);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,escapedDot)){
System.
out
.
println
(string +
"能够匹配正则:"
+ escapedDot);
}
else
{
System.
out
.
println
(string +
"不能够匹配正则:"
+ escapedDot);
}
}
for
(String string : strs) {
if
(
regexMatch
(string,characterClassDot)){
System.
out
.
println
(string +
"能够匹配正则:"
+ characterClassDot);
}
else
{
System.
out
.
println
(string +
"不能够匹配正则:"
+ characterClassDot);
}
}
}
private
static
boolean
regexMatch(String s, String regex) {
return
s.matches(regex);
}
}
运行结果:
0能够匹配正则:.
1能够匹配正则:.
2能够匹配正则:.
$能够匹配正则:.
{能够匹配正则:.
}能够匹配正则:.
.能够匹配正则:.
[能够匹配正则:.
]能够匹配正则:.
不能够匹配正则:.
0不能够匹配正则:\.
1不能够匹配正则:\.
2不能够匹配正则:\.
$不能够匹配正则:\.
{不能够匹配正则:\.
}不能够匹配正则:\.
.能够匹配正则:\.
[不能够匹配正则:\.
]不能够匹配正则:\.
不能够匹配正则:\.
0不能够匹配正则:[.]
1不能够匹配正则:[.]
2不能够匹配正则:[.]
$不能够匹配正则:[.]
{不能够匹配正则:[.]
}不能够匹配正则:[.]
.能够匹配正则:[.]
[不能够匹配正则:[.]
]不能够匹配正则:[.]
不能够匹配正则:[.]
可见\\.只能匹配点号,字符组内的[.]也只能匹配点号
也就是说点号在字符组内部,或者以转义形式给出的时候,只能匹配点号本身。
请注意:点号不能匹配换行符
小结:
-
字符组
用来规定某个位置能够出现的字符
在
[...]
结构中,方括号内列出的字符
用连字符可以表示范围
用[^...]表示排除型字符组,列出不容许出现的字符
排除型字符组仍然需要匹配一个字符
字符组简记法,常见的6种简记
特殊的简记法:点号,匹配除换行符之外的所有字符。
本文转自jooben 51CTO博客,原文链接:http://blog.51cto.com/jooben/317156