Java正则表达式使用例子
时间: 2024-01-04 16:20:06 浏览: 83
以下是一个Java正则表达式的使用例子:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String[] args) {
// 匹配
String input = "java123456Regular6543210Expression";
String regex = "\\d"; // 匹配数字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("匹配到的字符:" + matcher.group());
}
// 替换
String replaceRegex = "\\d{5,}"; // 匹配至少5个连续数字
String replacedString = input.replaceAll(replaceRegex, "#");
System.out.println("替换后的字符串:" + replacedString);
// 获取
String extractRegex = "\\d{5,}"; // 匹配至少5个连续数字
Pattern extractPattern = Pattern.compile(extractRegex);
Matcher extractMatcher = extractPattern.matcher(input);
if (extractMatcher.find()) {
System.out.println("提取到的字符串:" + extractMatcher.group());
}
}
}
```
阅读全文