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

1025
2023/7/12 13:55:06
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

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

  1. 匹配数字:
  • 表达式:\d+

  • 示例:

String text = "abc123def";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
// 输出:123
  1. 匹配字母:
  • 表达式:[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
  1. 匹配特定的字符:
  • 表达式:\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
  1. 匹配邮箱:
  • 表达式:\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
  1. 匹配中文:
  • 表达式:[\u4e00-\u9fa5]+

  • 示例:

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正则表达式的基本用法和实例,可以根据实际需求进行相应的调整和扩展。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java单元测试框架有哪些