加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – String.replaceAll()函数出错

发布时间:2020-12-15 02:06:53 所属栏目:Java 来源:网络整理
导读:我正在尝试以下代码: – String x = "asdfg/dgws";x.replaceAll("/",""); 但这是失败的.这给了我以下错误信息: – Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1 at java.lang.String.charAt(Un
我正在尝试以下代码: –

String x = "asdfg/dgws";
x.replaceAll("/","");

但这是失败的.这给了我以下错误信息: –

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(Unknown Source)
    at java.util.regex.Matcher.appendReplacement(Unknown Source)
    at java.util.regex.Matcher.replaceAll(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    at com.jai.SecLargest.main(SecLargest.java:13)

我无法弄清楚为什么会出现这种异常?

解决方法

String.replaceAll最终使用(或等同于使用) Matcher.replaceAll,其中包含以下内容:

Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above,and backslashes are used to escape literal characters in the replacement string.

虽然您可以根据AlexR的答案逃避反斜杠,但我强烈建议您使用替换:

String y = x.replace('/','');

这更清楚,IMO – 除非你真的试图通过正则表达式来表达模式,否则不要使用replaceAll.

另请注意,编写代码时无论如何都是无操作的;字符串在Java中是不可变的,因此replaceAll方法(以及类似的方法)返回对带有修改的新字符串的引用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读