“正则表达式 元字符 字符匹配符”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第128行: | 第128行: | ||
找到:c | 找到:c | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | |||
+ | |||
+ | |||
+ | === 示例:匹配 b-z 之间任意1个字符 === | ||
+ | <syntaxhighlight lang="java"> | ||
+ | import java.util.regex.Matcher; | ||
+ | import java.util.regex.Pattern; | ||
+ | |||
+ | public class RegExp03 { | ||
+ | |||
+ | public static void main(String[] args) { | ||
+ | |||
+ | String content = "a11c8"; | ||
+ | |||
+ | String regStr = "[b-z]"; //匹配 a-z 之间任意1个字符 | ||
+ | |||
+ | Pattern pattern = Pattern.compile(regStr); | ||
+ | |||
+ | Matcher matcher = pattern.matcher(content); | ||
+ | |||
+ | while (matcher.find()) { | ||
+ | |||
+ | System.out.println("找到:" + matcher.group(0)); | ||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight><syntaxhighlight lang="console"> | ||
+ | 找到:c | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | === 示例:匹配 A-Z 之间任意1个字符 === |
2022年11月15日 (二) 10:47的版本
https://www.bilibili.com/video/BV1Eq4y1E79W/?p=7
符号 | 符号 | 示例 | 解释 | 匹配输入 |
---|---|---|---|---|
[] | 可接收的字符列表 | [efgh] | e、f、g、h中的任意1个字符 | |
[^] | 不接收的字符列表 | [^abc] | 除a、b、c之外的任意1个字符,包括数组和特殊符号 | |
- | 连字符 | A-Z | 任意单个大写字母 | |
. | 匹配除 \n 以外的任何字符 | a..b | 以a开头,b结尾,中间包括2个任意字符的长度为4的字符串 | aaab、aefb、a35b、a#*b |
\\d | 匹配单个数字字符,相当于[0-9] | \\d{3}(\\d)? | 包含3个或4个数字的字符串 | 123、9876 |
\\D | 匹配单个非数字字符,相当于[^0-9] | \\D(\\d)* | 以单个非数字字符开头,后接任意个数字字符串 | a、A342 |
\\w | 匹配单个数字、大小写字母字符,相当于[0-9a-zA-Z] | \\d{3}\\w{4} | 以3个数字字符开头的长度为7的数字字母字符串 | 234abcd、12345Pe |
\\W | 匹配单个非数字、大小写字母字符,相当于[^0-9a-zA-Z] | \\W+\\d{2} | 以至少1个非数字字母字符开头,2个数字字符结尾的字符串 | #29、#?@10 |
示例:\\d\\d\\d 等价与 \\d{3}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 演示转义字符的使用
*/
public class RegExp02 {
public static void main(String[] args) {
String content = "abc.$)123";
//String regStr = "\\d\\d\\d";
String regStr = "\\d{3}";
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:" + matcher.group(0));
}
}
}
找到:123
示例:匹配 a-z 之间任意1个字符
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp03 {
public static void main(String[] args) {
String content = "a11c8";
String regStr = "[a-z]"; //匹配 a-z 之间任意1个字符
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:" + matcher.group(0));
}
}
}
找到:a
找到:c
示例:匹配 b-z 之间任意1个字符
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExp03 {
public static void main(String[] args) {
String content = "a11c8";
String regStr = "[b-z]"; //匹配 a-z 之间任意1个字符
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
System.out.println("找到:" + matcher.group(0));
}
}
}
找到:c