到目前为止,我能够将正则表达式用于句子,但如果仅输入答案本身则无法正常工作。
我在下面的函数中使用了正则表达式:
// 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;
非常感谢任何帮助。 感谢。
答案 0 :(得分:3)
我会以不同的方式解决这个问题。不要试图使用一个正则表达式,为什么不使用类似的东西:
String answer = ... // get the user's answer
if( answer.indexOf("crow") < answer.indexOf("feet") ) {
// "correct" answer
}
您仍需要对正确答案中的单词进行标记,然后检查循环以查看每个单词的索引是否小于后续单词的索引。
答案 1 :(得分:0)
我认为您不需要将结果拆分为“”。
如果我理解正确,你应该可以做类似
的事情String regex="^.*crow.*\\s+.*feet.*"
上述问题是它会匹配“feetcrow feetcrow”。
也许像
String regex="^.*\\s+crow.*\\s+feet\\s+.*"
这将强制该单词存在,而不是仅仅存在于随机字符块中。
答案 2 :(得分:0)
根据复杂程度,Bill的答案可能是最快的解决方案。如果你更喜欢正则表达式,我不会寻找任何空格,而是寻找单词边界。这样你就不必处理逗号,圆点等了:
String regex = "\\bcrow(?:\\b.*\\b)?feet\\b"
这应该匹配“乌鸦脚”以及“crowfeet”和“乌鸦,脚”。
必须按特定顺序匹配多个单词,您可以使用'(?:\ b。* \ b)将它们连接在一起?'无需任何额外的分类或检查。
答案 3 :(得分:0)
在比尔回答之后,我试试这个:
String input = // get user input
String[] tokens = input.split(" ");
String key1 = "crow";
String key2 = "feet";
String[] tokens = input.split(" ");
List<String> list = Arrays.asList(tokens);
return list.indexOf(key1) < list.indexOf(key2)