java - 带有 "or"运算符的正则表达式多个字符串

标签 java regex

我需要建立一个 java 正则表达式来识别以下 3 种情况:

  1. 以下字符的任意组合/数量:“ACTGactg:”

  • 任何单个问号“?”
  • 任意字符串“NTC”
  • 我将列出到目前为止我所尝试过的以及出现的错误。

    public static final VALID_STRING = "[ACTGactg:]*";
    // Matches the first case but not the second or third
    // as expected.
    
    public static final VALID_STRING = "\\?|[ACTGactg:]*";
    // Matches all 3 conditions when my understanding leads me to
    // believe that it should not except the third case of "NTC"
    
    public static final VALID_STRING = "?|[ACTGactg:]*";
    // Yields PatternSyntaxException dangling metacharacter ?
    

    我希望准确的内容如下:

    public static final VALID_STRING = "NTC|\\?|[ACTGacgt:]*";
    

    但我想确保如果我去掉“NTC”,任何“NTC”字符串都会显示为无效。

    这是我用来测试这些正则表达式的方法。

    private static boolean isValid(String thisString){
        boolean valid = false;
        Pattern checkRegex = Pattern.compile(VALID_STRING);
        Matcher matchRegex = checkRegex.matcher(thisString);
        while (matchRegex.find()){
            if (matchRegex.group().length != 0){
                valid = true;
            }
        }
        return valid;
    }
    

    这是我的结束语:

    1. “\\?”可以吗?正则表达式可能充当接受“NTC”字符串的通配符?

    2. 或运算符“|”这里合适吗?

    3. 使用这些或运算符时是否需要使用括号?

    以下是一些传入字符串示例:

    • A:C
    • T:G
    • AA:CC
    • T:C:A:G
    • NTC

    谢谢

    最佳答案

    是的,提供的正则表达式就可以了:

    public static final VALID_STRING = "NTC|\\?|[ACTGacgt:]+";
    

    ...

    boolean valid = str.matches(VALID_STRING);
    

    如果从正则表达式中删除 NTC|,字符串 NTC 就会变得无效。

    你可以自己测试一下here .

    关于java - 带有 "or"运算符的正则表达式多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28465676/

    相关文章:

    java - 使用 JSON/Gson 读取 JSON 字符串

    Python 正则表达式替换 : separate backreference from digit

    c# - 如何使用 .NET 正则表达式库匹配和删除反斜杠 "\"和 "\n"字符?

    java - 如何在RCP eclipse环境中将装饰器应用到标签提供者?

    java 类声明 <T>

    java - 球线碰撞

    c++ - 与 Boost 的正则表达式区分大小写的部分匹配

    java - 如何等待计划任务的第一次迭代完成?

    c# - 捕获所有符合正则表达式的组

    javascript - 正则表达式字母仅验证 javascript 提示