我需要建立一個Java正則表達式,將認識到以下3種情況:正則表達式的多個字符串用「或」運算符
- 下列字符的任意組合/金額:「ACTGactg:」
或
- 任何單個問號「?」
或
- 任何字符串 「NTC」
請問正則表達式可能作爲接受「NTC」字符串的通配符?
是或運算符「|」適合在這裏?
使用這些或操作符時是否需要使用括號?
- A:C
- T:G^
- AA:CC
- T:C:甲:ģ
- 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;
}
因此,這裏有我的收盤問題: 「\\?」
下面是一些例子傳入字符串:
謝謝
既然你有一個建議的解決方案,爲什麼不測試它,看看它是否工作,並試着用括號和不用括號? – DNA 2015-02-11 22:25:00
您使用哪種對象/方法來測試字符串? – RealSkeptic 2015-02-11 22:25:51
@DNA偉大的一點。我嘗試了許多不同的組合,並失去了所有單項結果的蹤跡。我想我在問什麼是規則/慣例。 – Malonge 2015-02-11 22:27:15