1. 程式人生 > >正則表示式中的邏輯運算子或(怎麼用邏輯運算子或連線兩個正則表示式)

正則表示式中的邏輯運算子或(怎麼用邏輯運算子或連線兩個正則表示式)

今天使用正則表示式是遇到一個問題, 磨了半天, 發現犯了個低階錯誤, 因此記錄下來加深印象

問題描述: 

我需要把 ^drawable(-[a-zA-Z0-9]+)*$  和  ^mipmap(-[a-zA-Z0-9]+)*$ 這兩個正則表示式用或的關係連線起來

我嘗試了一下方法都未成功!!

Pattern.compile("^drawable(-[a-zA-Z0-9]+)*$ | ^mipmap(-[a-zA-Z0-9]+)*$")

Pattern.compile("(^drawable(-[a-zA-Z0-9]+)*$) | (^mipmap(-[a-zA-Z0-9]+)*$)")

Pattern.compile("^drawable(-[a-zA-Z0-9]+)* | mipmap(-[a-zA-Z0-9]+)*$")

Pattern.compile("^(drawable | mipmap)(-[a-zA-Z0-9]+)*$")

原始碼如下:

import java.util.regex.Pattern;
public class MyClass {
    public static Pattern VALID_FOLDER_PATTERN = Pattern.compile("^drawable(-[a-zA-Z0-9]+)*$ | ^mipmap(-[a-zA-Z0-9]+)*$");
//public static Pattern VALID_FOLDER_PATTERN = Pattern.compile("(^drawable(-[a-zA-Z0-9]+)*$) | (^mipmap(-[a-zA-Z0-9]+)*$)");
//public static Pattern VALID_FOLDER_PATTERN = Pattern.compile("^drawable(-[a-zA-Z0-9]+)* | mipmap(-[a-zA-Z0-9]+)*$"); //public static Pattern VALID_FOLDER_PATTERN = Pattern.compile("^(drawable | mipmap)(-[a-zA-Z0-9]+)*$"); public static void main(String[] args) { if(VALID_FOLDER_PATTERN.matcher("drawable-xhdpi"
).matches()) { System.out.println("match"); } else { System.out.println("no match"); } if(VALID_FOLDER_PATTERN.matcher("mipmap-xhdpi").matches()) { System.out.println("match"); } else { System.out.println("no match"); } } }

糾結了半天發現自己畫蛇添足地把邏輯符號或(|) 的左右添加了一個空格(可能是寫程式碼習慣了-_-!!)

去掉作用兩邊的空格, 其實上面四個正則表示式都是正確的

總結:  在用邏輯符或連線正則表示式時, 千萬不要為了好看而在左右新增空格!! (其他符號也是一樣! 如^、$、*、.........不一而足...)