代码片段
按正则表达式 替换字符串
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
public String replaceAll(String regex, String replacement)
# 空白字符(White Space)替换为""
String str = " \n\r\f\t a \n\r\f\t b \n\r\f\t c \n\r\f\t ";
str.replaceAll("\\s+", ""); //abc
# 大写字符替换为空
String str = "AaBbCcDdEeFfGgHhJj";
str.replaceAll("[A-Z]", "") // abcdefghj
# 小写字母替换为空
String str = "AaBbCcDdEeFfGgHhJj";
str.replaceAll("[a-z]", "") // ABCDEFGHJ
按正则表达式 分割字符串
List<String> dalian = Pattern.compile("dalian").splitAsStream("Welcomedalianfordalian!").collect(Collectors.toList());
// [Welcome, for, !]
find() 与 matches() 的区别
Java Matcher对象中 find()
与 matches()
的区别
System.out.println(Pattern.compile("^$").matcher("").find()); //true
System.out.println(Pattern.compile("^$").matcher("").matches()); //true
System.out.println("".matches("^$")); //true
收集 符合正则表达式的子字符串
public static List<String> match(String input, String regex) {
Matcher matcher = Pattern.compile(regex).matcher(input);
List<String> matchedParts = new ArrayList<>();
while (matcher.find()) {
// matchedParts.add(matcher.group(0));
matchedParts.add(matcher.group());
}
return matchedParts;
}
// "abc aec def def", "a.c" → [abc, aec]
收集 符合正则表达式的捕获组
String line = "This order was placed for QT123! OK?";
Matcher matcher = Pattern.compile("(\\D*)(\\d+)(.*)").matcher(line);
if (matcher.find()) {
System.out.println("Found value: " + matcher.group(0)); // This order was placed for QT123! OK?
System.out.println("Found value: " + matcher.group(1)); // This order was placed for QT
System.out.println("Found value: " + matcher.group(2)); // 123
System.out.println("Found value: " + matcher.group(3)); // ! OK?
} else {
System.out.println("NO MATCH");
}
使用捕获组・反向引用
# 使用捕获组
String source = "1234567890, 12345, and 9876543210";
Matcher matcher = Pattern.compile("\\b(\\d{3})(\\d{3})(\\d{4})\\b").matcher(source);
while (matcher.find()) {
System.out.println("Phone: " + matcher.group() + ", Formatted Phone: (" + matcher.group(1) + ") " + matcher.group(2) + "-" + matcher.group(3));
}
//Phone: 1234567890, Formatted Phone: (123) 456-7890
//Phone: 9876543210, Formatted Phone: (987) 654-3210
# 使用反向引用
String formattedSource = matcher.replaceAll("($1) $2-$3");
//(123) 456-7890, 12345, and (987) 654-3210
asPredicate 断言字符串 是否符合正则表达式
public Predicate<String> asPredicate() {
return s -> matcher(s).find();
}
Predicate<String> predicate = Pattern.compile("dalian").asPredicate();
System.out.println(predicate.test("welcome dalian")); //true
System.out.println(predicate.test("welcome dalian1")); //true
System.out.println(predicate.test("welcome dalia")); //false
转义字符 视为普通文本
# Pattern.quote("*.txt")会返回 "\\Q*.txt\\E" ,其中\Q和\E是转义序列,它们告诉解析器从\Q到\E内的所有内容都应该被视为普通文本。
boolean isMatch = Pattern.compile(Pattern.quote("*.txt")).matcher("myFile.txt").matches();
// 返回false,因为 "myFile.txt" 不等于 "*.txt" 字符串本身
常见正则表达式
验证日期
✅ [Ref] 日期验证正则表达式
如何匹配""
包含.
的字符串
✅ 包含.
的字符串:[^""]*\.[^""]*
System.out.println(Pattern.compile("[^\"\"]*\\.[^\"\"]*").matcher("").find()); //false
System.out.println(Pattern.compile("[^\"\"]*\\.[^\"\"]*").matcher(".").find()); //true
System.out.println(Pattern.compile("[^\"\"]*\\.[^\"\"]*").matcher("1.").find()); //true
System.out.println(Pattern.compile("[^\"\"]*\\.[^\"\"]*").matcher(".1").find()); //true
System.out.println(".".matches("[^\"\"]*\\.[^\"\"]*")); //true
【代码排查】找抛出异常的地方
(,|\+|\))(| )(e|ex|exception)(| )|(printStackTrace|getStackTrace)
算法题
[中等] HJ17.坐标移动
1、合法坐标为A(或者D或者W或者S) + 数字(两位以内)
2、坐标之间以;分隔。
3、非法坐标点需要进行丢弃。如AA10; A1A; $%$; YAD; 等。
List<String> strs = Arrays.stream(str.split(";")).collect(Collectors.toList());
List<String> actions = strs.stream()
.filter(a -> a != null && a.length() > 0)
.filter(word -> word.matches("[WASD][0-9]{1,2}"))
.collect(Collectors.toList());
[中等] HJ20.密码验证合格程序
// 包括大小写字母.数字.其它符号,以上四种至少三种
private static boolean getMatch(String str) {
int count = 0;
if (Pattern.compile("[A-Z]").matcher(str).find()) {
count++;
}
if (Pattern.compile("[a-z]").matcher(str).find()) {
count++;
}
if (Pattern.compile("[0-9]").matcher(str).find()) {
count++;
}
if (Pattern.compile("[^a-zA-Z0-9]").matcher(str).find()) {
count++;
}
if (count >= 3) {
return false;
} else {
return true;
}
}