java 正则表达式总结
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
Java正则表达式是一种用于文本匹配和搜索的强大工具。以下是一些常用的Java正则表达式示例:
- 验证电子邮件地址:
String emailPattern = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher("example@test.com");
boolean isValid = matcher.matches(); // true or false
- 验证电话号码(例如:美国的格式):
String phonePattern = "\\d{3}-\\d{3}-\\d{4}";
Pattern pattern = Pattern.compile(phonePattern);
Matcher matcher = pattern.matcher("123-456-7890");
boolean isValid = matcher.matches(); // true or false
- 查找字符串中的数字:
String numberPattern = "\\d+";
Pattern pattern = Pattern.compile(numberPattern);
Matcher matcher = pattern.matcher("There are 10 apples and 20 oranges.");
while (matcher.find()) {
System.out.println(matcher.group()); // 输出数字
}
- 替换字符串中的字符:
String replacePattern = "apple";
String replaceWith = "orange";
Pattern pattern = Pattern.compile(replacePattern);
Matcher matcher = pattern.matcher("I like apples and oranges.");
String result = matcher.replaceAll(replaceWith);
System.out.println(result); // 输出 "I like oranges and oranges."
- 分割字符串:
String splitPattern = ",";
Pattern pattern = Pattern.compile(splitPattern);
String[] result = pattern.split("apple,orange,banana");
// result = ["apple", "orange", "banana"]
以上示例展示了如何使用Java正则表达式进行基本的验证、查找、替换和分割操作。根据需要,可以创建更复杂的正则表达式来进行更高级的文本处理。
评论已关闭