正则表达式中的逻辑运算符或(怎么用逻辑运算符或连接两个正则表达式)

今天使用正则表达式是遇到一个问题, 磨了半天, 发现犯了个低级错误, 因此记录下来加深印象

问题描述:

我需要把 ^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");

}

}

}

纠结了半天发现自己画蛇添足地把逻辑符号或(|) 的左右添加了一个空格(可能是写代码习惯了-_-!!)

去掉作用两边的空格, 其实上面四个正则表达式都是正确的

总结: 在用逻辑符或连接正则表达式时, 千万不要为了好看而在左右添加空格!! (其他符号也是一样! 如^、$、*、.........不一而足...)