正則表達式不是正確的工具......它們應該用於從左到右匹配,不按隨機順序計算各種字符。你最好有一個驗證字符串hello
,循環輸入字符串中的每個字符,並檢查字符是否存在(如果是,則從驗證字符串中移除該字符並繼續,否則輸入失敗)。
這裏是一個quick example I whipped up in Java:
public static boolean testString(String testString)
{
String allowedCharacters = "hello";
for(int i = 0; i < testString.length(); i++) {
int position = allowedCharacters.indexOf(testString.charAt(i));
if(position == -1) {
System.out.println(testString + " - fail");
return false;
} else {
allowedCharacters = allowedCharacters.substring(0, position)
+ allowedCharacters.substring(position + 1);
}
}
System.out.println(testString + " - success");
return true;
}
與調用示例輸出功能:
testString("hello"); // hello - success
testString("hell"); // hell - success
testString("lol"); // lol - success
testString("heel"); // heel - fail
testString("loo"); // loo - fail
來源
2015-03-31 16:09:56
Sam
爲什麼'lol'有效的條目? – 2015-03-31 15:43:12
好吧,我希望用戶能夠從給定的字母組合中創建任何單詞 – kfcobrien 2015-03-31 15:51:07
解釋有效和無效答案中的變體,並強化語言以提供完整的問題。 – rfornal 2015-03-31 18:42:43