【代码总结】正则 代码片段 & 算法题

代码片段

按正则表达式 替换字符串

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值