Java Regex

Posted by Adam on August 24, 2022
```java import java.util.regex.*; public class Main { public static void main(String[] args) { // 使用正則表達式進行大小寫不敏感匹配 String regex = "(?i)(in|out)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher("InOut"); System.out.println(matcher.find()); // true System.out.println("InnOxtoUt".replaceAll(regex, "###")); // ###nOxt### System.out.println("InnOxtoUt".replaceAll("(?i)(in|out).*", "$1")); // In System.out.println("InnOxtoUt".replaceAll(".*(?i)(in|out)", "$1")); // oUt /** * 迴文格式 */ Pattern p = Pattern.compile("(.)(.)(.).?\\3\\2\\1"); Matcher m = p.matcher("abcdcbaabccba"); while(m.find()) { System.out.println(m.group()); } // abcdcba // abccba System.out.println("InnOxtoUt".replaceAll(regex, "###")); // ###nOxt### System.out.println("abcd924bccba".replaceAll("\\D*(\\d*)\\D*", "$0")); // abcd924bccba System.out.println("abcd924bccba".replaceAll("\\D*(\\d*)\\D*", "$1")); // 924 /** * 陽春版取得 json 欄位方法 */ regex = "\\s*\"code\"\\s*:\\s*(\\d*)"; final String string = "{\"code\":100, \"msg\":\"message\", \"data\":{\"points\":\"9\", \"status\":\"Y\"}}"; pattern = Pattern.compile(regex, Pattern.MULTILINE); matcher = pattern.matcher(string); while (matcher.find()) { System.out.println("Full match: " + matcher.group(0)); System.out.println("match 1: " + matcher.group(1)); for (int i = 1; i <= matcher.groupCount(); i++) { System.out.println("Group " + i + ": " + matcher.group(i)); } } // Full match: "code":100 // match 1: 100 // Group 1: 100 } } ```