我需要建立一个java regex,它将识别以下3种情况:
或
或
我将列出我迄今尝试过的内容和出现的错误。
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”字符串都将显示为无效。
下面是我用来测试这些regexs的方法。
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;
}
以下是我最后的几个问题:
下面是一些传入字符串的示例:
谢谢
发布于 2015-02-11 14:41:25
是的,所提供的regex是可以的:
public static final VALID_STRING = "NTC|\\?|[ACTGacgt:]+";
..。
boolean valid = str.matches(VALID_STRING);
如果从正则表达式中删除NTC|
,则字符串NTC将无效。
您可以对其进行测试,并自行实验这里。
发布于 2015-02-11 14:44:17
由于您使用的是Matcher.find()
方法,所以您需要在字符串中的任何位置查找您的模式。
这意味着字符串A:C
、T:G
、AA:CC
等完全匹配。但是NTC
呢?
它匹配,因为find()
在任何地方寻找匹配。它的TC
部分匹配,因此您得到了true
。
如果希望只匹配字符串的全部内容,可以使用match()
方法,或者使用^
和$
。
请注意,如果您将模式更改为[ACTGactg:]+
而不是[ACTGactg:]*
,则不必检查匹配是否长于0。
https://stackoverflow.com/questions/28465676
复制相似问题