Java中常用的正则表达式函数及其应用举例
发布时间:2023-09-21 05:25:38
正则表达式是一种用于匹配、查找、替换字符串的强大工具,Java中提供了大量正则表达式函数供开发者使用。
1. match函数:用于检查字符串是否符合正则表达式的模式。
例如,判断一个字符串是否为合法的手机号码:
String regex = "^1[34578]\\d{9}$";
String phoneNumber = "18812345678";
boolean isMatch = phoneNumber.matches(regex);
2. find函数:用于在字符串中查找与正则表达式匹配的单个子字符串。
例如,从一个字符串中提取所有的 email 地址:
String regex = "\\b[A-Za-z\\d]+@[A-Za-z\\d]+\\.[A-Za-z]{2,3}\\b";
String text = "This is an example email: example@domain.com";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String email = matcher.group();
System.out.println(email);
}
3. replace函数:用于将字符串中与正则表达式匹配的部分替换为指定的内容。
例如,从一个字符串中删除所有的标点符号:
String regex = "\\p{Punct}";
String text = "Hello, World!";
String result = text.replaceAll(regex, "");
System.out.println(result); // output: Hello World
4. split函数:用于根据正则表达式将字符串拆分成数组。
例如,按照空格将一个句子拆分成单词:
String regex = "\\s+";
String sentence = "This is a sentence.";
String[] words = sentence.split(regex);
for (String word : words) {
System.out.println(word);
}
5. matches函数:用于判断一个字符串是否与正则表达式完全匹配。
例如,判断一个字符串是否为合法的日期格式(dd/MM/yyyy):
String regex = "\\d{2}/\\d{2}/\\d{4}";
String date = "01/01/2022";
boolean isMatch = date.matches(regex);
6. appendReplacement和appendTail函数:用于在字符串中查找并替换匹配的部分。
例如,将一个字符串中的所有数字替换为 '#':
String regex = "\\d+";
String text = "The number is 123456.";
StringBuffer result = new StringBuffer();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matcher.appendReplacement(result, "#");
}
matcher.appendTail(result);
System.out.println(result.toString()); // output: The number is ######.
以上是Java中常用的正则表达式函数及其应用举例,开发者可以根据具体需求选择合适的函数来进行字符串处理。使用正则表达式可以快速、灵活地处理各种文本操作。
