简体   繁体   English

不匹配时Java replaceAll方法返回null

[英]Java replaceAll method return null when no match

I have some existing Java code我有一些现有的 Java 代码

Pattern regex = Pattern.compile(regexStr, Pattern.CASE_INSENSITIVE);        
Matcher m = regex.matcher(value);
String replace= m.replaceAll(regexReplaceStr);

This is hard-coded in my project.I can't change it.这是我的项目中的硬编码。我无法更改它。 I can only set values regexStr and regexReplaceStr by configuration.我只能通过配置设置值regexStrregexReplaceStr What I need to do is我需要做的是

  • If there is a match, return the original string如果匹配,则返回原始字符串
  • If there is no match, return an empty string如果不匹配,则返回一个空字符串

What should my strings regexStr and regexReplaceStr be in this case?在这种情况下,我的字符串regexStrregexReplaceStr应该是什么?

So for example, I have例如,我有

regexStr = "^[^_]+_(.*)$"
regexReplace = "$0"

So now if the input string is AA_BBB , the value returned is AA_BBB .所以现在如果输入字符串是AA_BBB ,返回的值是AA_BBB Now, if the input string is AABBB , I want it to return an empty string .现在,如果输入字符串是AABBB ,我希望它返回一个空字符串 How can this be done?如何才能做到这一点?

First of all, the code is unclear.首先,代码不清楚。 There is no reference to 'value'...没有提到“价值”...

Matcher m = regex.matcher(value);
                           ^ ^

And there is also no context about this piece of code.并且也没有关于这段代码的上下文。
Is it used as a method?是否用作方法? A user input?用户输入?

You could add this after your code:您可以在代码后添加:

if (replace == null) {
    replace = "";
}

It would then replace null by an empty String.然后它将用空字符串替换 null。

However I did the same code as you but it never returned null...但是我做了和你一样的代码,但它从来没有返回空......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM