如何在pattern.compile中处理Null?

Sam*_*rat 2 java design-patterns

如何在使用pattern.compile时处理NULL?我正在使用以下行来比较字符串

if(Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find())
Run Code Online (Sandbox Code Playgroud)

在某些情况下,s1可以为NULL,显然它会抛出Null指针Exception.我知道这可以通过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;
    }
}
Run Code Online (Sandbox Code Playgroud)

S1和S3是在迭代器上匹配的输入.

Ray*_*Ray 8

你必须检查null; 例如,

if(s1 != null && Pattern.compile(Pattern.quote(s2), Pattern.CASE_INSENSITIVE).matcher(s1).find()))
Run Code Online (Sandbox Code Playgroud)


Joa*_*uer 5

Pattern.matcher()NullPointerException传入时将始终抛出a null,因此:不,没有其他方法,您必须null显式检查。