在我写的程序中,我有以下代码为单词创建正则表达式,并从一系列不同的ArrayLists中检索与其匹配的所有单词。
public ArrayList<String> solveWord(String str)
{
String regex = "";
String[] strArr = str.split("");
for (String temp : strArr)
{
if (temp.equals(" "))
{
regex = regex + "[a-z]";
}
else
{
String s = "[" + temp + "]";
regex = regex + s;
}
}
int x = str.length();
ArrayList<String> m = null;
System.out.println("2ns");
switch (x)
{
case 1: break;
case 2: m = let2;
break;
case 3: m = let3;
break;
case 4: m = let4;
break;
case 5: m = let5;
break;
case 6: m = let6;
break;
case 7: m = let7;
break;
case 8: m = let8;
break;
case 9: m = let9;
break;
case 10: m = let10;
break;
case 11: m = let11;
break;
case 12: m = let12;
break;
case 13: m = let13;
break;
case 14: m = let14;
break;
case 15: m = let15;
break;
case 16: m = let16;
break;
}
System.out.println(" ns");
ArrayList<String> trans = retrieve(str,m,regex);
return trans;
}
private ArrayList<String> retrieve(String word, ArrayList<String> arr, String reg)
{
ArrayList<String> ex = arr;
ArrayList<String> matches = new ArrayList<String>();
for (String temp : ex)
{
if (temp.matches(reg))
{
matches.add(temp);
}
}
return matches;
}
当我从另一个类调用solve(String str)时,行“strArr = str.split(”“);抛出一个空指针异常。我遇到的另一个问题是当我自己测试这个类时,if(temp.matches(reg))行给出以下错误。
Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 12
[][h][a-z][h]
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.clazz(Unknown Source)
at java.util.regex.Pattern.sequence(Unknown Source)
at java.util.regex.Pattern.expr(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.matches(Unknown Source)
at java.lang.String.matches(Unknown Source)
at Words.fillInTheBlanks.retrieve(fillInTheBlanks.java:238)
at Words.fillInTheBlanks.solveWord(fillInTheBlanks.java:228)
at Words.tester.main(tester.java:12)
有人可以帮忙吗?
答案 0 :(得分:3)
你的正则表达式中不能有空方括号[]
。在生成正则表达式之前,您必须检查temp
是否为空:
if (temp.equals(" "))
{
regex = regex + "[a-z]";
}
else if (temp.length() > 0)
{
String s = "[" + temp + "]";
regex = regex + s;
}
对于NullPointerException,它在行String[] strArr = str.split("");
中发生的唯一可能性是str
为空。
答案 1 :(得分:0)
这里的分裂功能问题是;你需要通过使用一些字符串进行拆分,并且该字符串不能像&#34;&#34; 。 如果你想按空格分割,那么写&#34; &#34;