有关String.replaceAll()和String.replaceFirst()方法的问题 [英] Question about the String.replaceAll() and String.replaceFirst() method

查看:184
本文介绍了有关String.replaceAll()和String.replaceFirst()方法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对一段字符串做一个简单的字符串替换操作。我遇到了以下问题并希望得到一些建议。

I need to do a simple string replace operation on a segment of string. I ran into the following issue and hope to get some advice.


  1. 在我得到的原始字符串中,我可以替换字符串,例如< div class =more> to other else。

  2. 但是,如果我想要替换,请使用相同的原始字符串一个很长的字符串,如下所示,它将无法正常工作。通话结束后没有任何内容被取代。

  1. In the original string I got, I can replace the string such as <div class="more"> to something else.
  2. BUT, in the same original string, if I want to replace a much long string such as the following, it won’t work. Nothing gets replaced after the call.

< div class =more>< a href ?=HTTP://SERVER_name/profiles/atom/mv/theboard/entries/related.do电子邮件= xyz.com&放大器;放大器; PS = 20&放大器;放大器;因为= 1273518953218&放大器;放大器; sinceEntryId = ABC-DEF-123- 456>更多...< / a>< / div>

我尝试了这两种方法:

originalString.replaceFirst(moreTag, newContent);
originalString.replaceAll(moreTag, newContent);

提前致谢。

推荐答案

你需要掌握替换的结果并进一步使用它:

You need to get hold of the result of the replacement and use it further:

String newString = originalString.replaceFirst(moreTag, newContent);
System.out.println(newString);

说明:Java中的字符串是不可变的 java.lang.String 的行为方法不会更改内部值。他们将返回修改后的结果。

Explanation: strings in Java are immutable. The behavioral methods of java.lang.String won't change the internal value. They instead will return the modified result.

如果仍然没有返回所需的结果,那么 moreTag 根本没有匹配任何东西。您提到的方法需要正则表达式。您可以在 模式 javadoc如何构成有效的正则表达式模式。

If that still doesn't return the desired result, then the moreTag simply didn't match anything. The methods you mentioned expects a regular expression. You can find in the Pattern javadoc how to compose a valid regex pattern.

这篇关于有关String.replaceAll()和String.replaceFirst()方法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆