【发布时间】:2015-04-12 11:49:15
【问题描述】:
我需要建立一个能够识别以下 3 种情况的 java 正则表达式:
- 以下字符的任意组合/数量:“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”字符串的通配符?
or 运算符是“|”吗这里合适吗?
在使用这些或运算符时是否需要使用括号?
以下是一些传入字符串的示例:
- A:C
- T:G
- AA:CC
- T:C:A:G
- NTC
- ?
谢谢
【问题讨论】:
-
既然你有一个提议的解决方案,为什么不直接测试它,看看它是否有效,然后在有或没有括号的情况下尝试它?
-
您使用哪个对象/方法来测试字符串?
-
@DNA 好点。我尝试了许多不同的组合,却忘记了所有单独的结果。我想我在问规则/约定是什么。
-
@RealSkeptic 给我一秒钟,我将包括我正在使用的方法。
-
你能提供一些应该匹配和不应该匹配的字符串示例吗?正则表达式是否应该匹配整个字符串?喜欢
NTC、Atgc、??..