我需要建立一个 java 正则表达式来识别以下 3 种情况:
- 以下字符的任意组合/数量:“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;
}
这是我的结束语:
“\\?”可以吗?正则表达式可能充当接受“NTC”字符串的通配符?
或运算符“|”这里合适吗?
使用这些或运算符时是否需要使用括号?
以下是一些传入字符串示例:
- 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/