Java正则表达式是一种强大的文本处理工具,它可以用来匹配、查找、替换和分割字符串,下面是一些Java正则表达式的用法示例:
1. 匹配字符串是否符合特定模式
String pattern = "^[a-zA-Z]+$"; // 匹配由字母组成的字符串 String str = "hello"; boolean isMatch = str.matches(pattern); // 返回 true
2. 查找字符串中符合特定模式的子串
String text = "hello world"; String pattern = "world"; String result = text.replaceAll(pattern, "Java"); // 替换为 "hello Java"
3. 分割字符串为多个部分
String text = "apple,banana,orange"; String[] parts = text.split(","); // 分割为 ["apple", "banana", "orange"]
4. 替换字符串中的特定模式
String text = "hello world"; String pattern = "world"; String newText = text.replace(pattern, "Java"); // 替换为 "hello Java"
5. 使用正则表达式进行复杂匹配和查找操作
String text = "The quick brown fox jumps over the lazy dog"; String pattern = "o[aeiou]"; // 匹配以元音字母开头的字母o Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(text); while (m.find()) { System.out.println(m.group()); // 输出 "o", "o", "o" 和 "o" }