TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 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", "$","{","}",".","[","]","
- "};
- 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种简记
特殊的简记法:点号,匹配除换行符之外的所有字符。
源码下载:http://file.javaxxz.com/2014/10/31/000028609.zip |
|