正則表達式是一種用來匹配字符序列的模式,用于檢索、替換和分割字符串。在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正則表達式的基本用法和實例,可以根據實際需求進行相應的調整和擴展。