How to handle null when using Pattern.compile? I’m using the following line to compare strings:
Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()
There are some cases where s1 can be null and obviously it throws NullPointerException. I know this could be handled by another if condition to s1, but I would like to know is there’s an alternate solution.
EDIT
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 and s3 are inputs which are matched over iterator.
Pattern.matcher()will always throw aNullPointerExceptionwhen you pass innull, so: no, there is no other way, you’ll have to check fornullexplicitly.