使用Pattern.compile
时如何处理null
?我使用以下行来比较字符串:
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()
在某些情况下,s1
可能为 null
,并且显然它会抛出 NullPointerException
。我知道这可以通过 s1
的另一个 if
条件来处理,但我想知道是否有替代解决方案。
编辑
Iterator iter = sampleList().iterator();
while (iter.hasNext()) {
SampleObj so = (SampleObj) iter.next();
if (!s1.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s1), Pattern.CASE_INSENSITIVE).matcher(so.getS1()).find())
match = true;
else
match = false;
}
if (!s3.equalsIgnoreCase("")) {
if (Pattern.compile(Pattern.quote(s3), Pattern.CASE_INSENSITIVE).matcher(so.getS3()).find())
match = true;
else
match = false;
}
}
s1
和 s3
是通过迭代器匹配的输入。
最佳答案
你必须检查是否为空;例如,
if(s1 != null && Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()))
关于java - 如何处理Pattern.compile中的null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6187176/