java - 删除多个正则表达式的交集?

标签 java regex

 Pattern[] a =new Pattern[2];
 a[0] = Pattern.compile("[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d");
 a[1] = Pattern.compile("Rs[.]?\\s*[\\d,]*[.]?\\d*\\d");

例如:Rs.150a[1] 检测到和 150a[0] 检测到. 如何删除此类交叉点并让它仅通过 a[1] 检测但不是 a[0]

最佳答案

您可以在正则表达式中使用 | 运算符。然后调用方法Matcher#group(int)查看您的输入适用于哪种模式。如果匹配组为空,此方法返回 null

示例代码

public static void main(String[] args) {
    // Build regexp
    final String MONEY_REGEX = "[$£€]?\\s*\\d*[\\.]?[pP]?\\d*\\d";
    final String RS_REGEX = "Rs[.]?\\s*[\\d,]*[.]?\\d*\\d";

    // Separate them with '|' operator and wrap them in two distinct matching groups
    final String MONEY_OR_RS = String.format("(%s)|(%s)", MONEY_REGEX, RS_REGEX);

    // Prepare some sample inputs
    String[] inputs = new String[] { "$100", "Rs.150", "foo" };

    Pattern p = Pattern.compile(MONEY_OR_RS);

    // Test each inputs
    Matcher m = null;
    for (String input : inputs) {
        if (m == null) {
            m = p.matcher(input);
        } else {
            m.reset(input);
        }

        if (m.matches()) {
            System.out.println(String.format("m.group(0) => %s\nm.group(1) => %s\n", m.group(1), m.group(2)));
        } else {
            System.out.println(input + " doesn't match regexp.");
        }
    }
}

输出

    m.group(0) => $100
    m.group(1) => null

    m.group(0) => null
    m.group(1) => Rs.150

    foo doesn't match regexp.

关于java - 删除多个正则表达式的交集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17145516/

相关文章:

regex - 删除第二个逗号之前的文本 ('' ,") 字符串替换模式

java - 一个类如何同时扩展和实现其他类和接口(interface)?

java - 无法执行目标 org.apache.maven.plugins :maven-surefire-plugin:2. 4.3:test (default-test) on project smrr: There are test failures

ios - 将 iOS .strings 文件解析为 perl 哈希

JavaScript 字符串替换 - 如何在替换字符串中使用匹配的变量?

javascript - 正则表达式:匹配字符串中所有单词的模式

javascript - 正则表达式通过特定符号查找单词

java - 类加载器和重复的包和类名

java - 应用程序不能使用模块的模块

java - 将 Java Bean 扁平化为 map