Java

Java正则表达式的基本用法和实例大全

小云
104
2023-08-11 13:55:06
栏目: 编程语言

正则表达式是一种用来匹配字符序列的模式,用于检索、替换和分割字符串。在Java中,可以使用java.util.regex包下的Pattern和Matcher类来进行正则表达式的使用。

下面是一些常用的Java正则表达式的基本用法和实例:

  1. 匹配数字:
String text = "abc123def";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:123
  1. 匹配字母:
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
  1. 匹配特定的字符:
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
  1. 匹配邮箱:
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
  1. 匹配中文:
String text = "你好,世界!";
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:你好,世界!
  1. 替换字符串:
String text = "abc123def";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll("X");
System.out.println(result);
// 输出:abcXdef
  1. 分割字符串:
String text = "a,b,c";
String[] parts = text.split(",");
for (String part : parts) {
System.out.println(part);
}
// 输出:a, b, c

以上是一些常用的Java正则表达式的基本用法和实例,可以根据实际需求进行相应的调整和扩展。

0
看了该问题的人还看了