简体   繁体   English

为什么string.replaceAll行为异常

[英]why is string.replaceAll misbehaving

I have always used string.replaceAll() without any problems. 我一直使用string.replaceAll()没有任何问题。

But now I'm just stumped... 但是现在我很困惑...

Here is my code 这是我的代码

public static String getVersionName() {
    String versionName = null;
    versionName = "v"+packageInfo.versionName;
    versionName = versionName.replaceAll(".","_");
    return versionName;
}

versionName before replaceAll is v1.0.4 replaceAll之前的versionName为v1.0.4

expected result is v1_0_4 actual result is either v____ or _____ it varies for some reason, and is never the expected result. 预期结果是v1_0_4实际结果是v_________ ,由于某种原因而有所不同,并且永远不是预期结果。

Why is this happening? 为什么会这样呢? How can I fix it? 我该如何解决?

It's happening because replaceAll uses regular expressions. 发生这种情况是因为replaceAll使用正则表达式。

You need to escape the "." 您需要转义“。” using "\\\\." 使用“ \\\\”。

It's happening because replaceAll expects a regex. 之所以这样,是因为replaceAll需要一个正则表达式。 You should probably use replace instead (which still replaces all occurences), since you only want to match a single character. 您可能应该使用replace代替(它仍将替换所有出现的情况),因为您只想匹配一个字符。

So using versionName = versionName.replace('.','_'); 因此,使用versionName = versionName.replace('.','_'); on v1.0.4 will give you v1_0_4 as a result. 在v1.0.4上的结果将是v1_0_4。

replaceAll() uses regular expressions, within which . replaceAll()使用正则表达式,其中. matches any character . 匹配任何字符

Your options are to escape the . 您的选择是逃脱. so it just means "." 所以它的意思是“。” again, using \\\\. 再次使用\\\\.

Or, if you don't need regular expressions (You don't in this case), you should use replace() instead, which will be faster and you won't now have two problems to solve . 或者,如果不需要正则表达式(在这种情况下不需要),则应改为使用replace() ,这样会更快,并且现在不会有两个问题需要解决

versionName = versionName.replace(".","_");

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

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