Java正则表达式的基本用法和实例大全
正则表达式是一种用来匹配字符序列的模式,用于检索、替换和分割字符串。在Java中,可以使用java.util.regex包下的Pattern和Matcher类来进行正则表达式的使用。
下面是一些常用的Java正则表达式的基本用法和实例:
- 匹配数字:
-
表达式:\d+
-
示例:
String text = "abc123def";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:123
- 匹配字母:
-
表达式:[a-zA-Z]+
-
示例:
String text = "abc123def";
Pattern pattern = Pattern.compile("[a-zA-Z]+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:abc, def
- 匹配特定的字符:
-
表达式:\w
-
示例:
String text = "abc123def";
Pattern pattern = Pattern.compile("\\w");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:a, b, c, 1, 2, 3, d, e, f
- 匹配邮箱:
-
表达式:\w+@\w+.\w+
-
示例:
String text = "abc@example.com";
Pattern pattern = Pattern.compile("\\w+@\\w+\\.\\w+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:abc@example.com
- 匹配中文:
-
表达式:[\u4e00-\u9fa5]+
-
示例:
String text = "你好,世界!";
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:你好,世界!
- 替换字符串:
- 示例:
String text = "abc123def";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll("X");
System.out.println(result);
// 输出:abcXdef
- 分割字符串:
- 示例:
String text = "a,b,c";
String[] parts = text.split(",");
for (String part : parts) {
System.out.println(part);
}
// 输出:a, b, c
以上是一些常用的Java正则表达式的基本用法和实例,可以根据实际需求进行相应的调整和扩展。
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。