嘿大家, 我在設置正則表達式時遇到了一些小難題,該正則表達式將用戶在文本框中輸入的句子評估爲關鍵字。實質上,關鍵字必須從一個連續輸入到另一個,並且可以在之前,之間和之後具有任意數量的字符或空格(即,如果關鍵字是「烏鴉」和「英尺」,則烏鴉必須位於因此考慮到這一點,這個陳述應該是有效的「)。在一定程度上,字符和空間(我希望關鍵字在開始和結尾至少有一個空格緩衝區)是完全可選的,主要關心的是關鍵字是否按照正確的順序輸入。用於驗證問題答案的正則表達式
到目前爲止,我能夠在一個句子中使用正則表達式工作,但如果僅輸入答案本身,則無法工作。
我在下面的函數中使用正則表達式:
// Comparing an answer with the right solution
protected boolean checkAnswer(String a, String s) {
boolean result = false;
//Used to determine if the solution is more than one word
String temp[] = s.split(" ");
//If only one word or letter
if(temp.length == 1)
{
if (s.length() == 1) {
// check multiple choice questions
if (a.equalsIgnoreCase(s)) result = true;
else result = false;
}
else {
// check short answer questions
if ((a.toLowerCase()).matches(".*?\\s*?" + s.toLowerCase() + "\\s*?.*?")) result = true;
else result = false;
}
}
else
{
int count = temp.length;
//Regular expression used to
String regex=".*?\\s*?";
for(int i = 0; i<count;i++)
regex+=temp[i].toLowerCase()+"\\s*?.*?";
//regex+=".*?";
System.out.println(regex);
if ((a.toLowerCase()).matches(regex)) result = true;
else result = false;
}
return result;
任何幫助將大大讚賞。 謝謝。
關鍵詞「魚尾紋」僅僅是一個例子,它可以是任何數量的不同的詞。 – Steve 2011-03-16 23:37:28