1

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. 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?email=xyz.com&amp;ps=20&amp;since=1273518953218&amp;sinceEntryId=abc-def-123-456">More...</a></div>

I tried these two methods:

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

Thanks in advance.

4
  • 1
    Can't access your "More" link. Commented May 13, 2010 at 13:37
  • I can't seem to browse to that link of yours Commented May 13, 2010 at 13:38
  • 1
    It wasn't meant to be a link, I think -- it was a code sample describing a link. I've added code formatting. Commented May 13, 2010 at 13:40
  • Better give us the explicit code: what are you putting in the "originalString" and "moreTag" variables when you do originalString.replaceAll(moreTag, newContent), and how are you checking for success? Commented May 13, 2010 at 13:42

4 Answers 4

6

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);

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.

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.

Sign up to request clarification or add additional context in comments.

4 Comments

hello,all Thanks for the quick responses. I defined the moreTag like this where I considered the escape character, and replaceAll() works in this case. String moreTag = new String("<div class=\"more\">"); However, when I construct the longer string such as the one showed in my original question, I did not do anything about the double quotes or http:// I got the string like this: String removedMoreTag=finalContent.substring(moreStartIndex, moreSecondIndex+6); Is this the problem? Should I do something about the double quotes in this removedMoreTag before making the replaceAll() call?
You shouldn't parse HTML with regex. You need to parse HTML with a HTML parser. I recommend JSoup for this.
Hello, I am back again. I was able to find the solution using Java 1.5 API (String myFinalContent = finalContent.replaceFirst(Pattern.quote(string1), Matcher.quoteReplacement(string2));). Now, I just found out that in the codestream I am building, I can only use Java 1.4 API. Could somebody advice me how I can easily convert a string to REGULAR EXPRESSION? I did lots of research last night but could not find an answer. Really appreciated....
@Java Doe: You just need to manually quote the pattern and the replacement. Do System.out.println() of them in Java 1.5 to learn how they should actually look like and use that instead. Or look/copy the source of those Java 1.5 methods.
0

Can you show us your code ?

Are you aware that your moreTag string (the first argument to replaceFirst/replaceAll) is assumed to be a regular expression ?

If you dont want regular expressions here, you can use the plain replace method.

Comments

0

Strings are immutable, do you save the result of replace operation?

Test you regular expression if it really matches what do you think, you'll find some tools for that online. Especially take care of proper escaping of special characters.

Also, if you do not need regular expressions, consider using StringTokenizer and StringBuilder.

Comments

0

Here's an example of replaceAll and replaceFirst usage:

    String s = "Hi there! John here!";

    s = s.replaceAll("ere", "arrr");
    System.out.println(s);
    // prints "Hi tharrr! John harrr!"

    s = s.replaceFirst("!", "?");
    System.out.println(s);
    // prints "Hi tharrr? John harrr!"

As others have mentioned, both are actually regex-based:

    System.out.println("Hello???".replaceAll("?", "!"));
    // throws PatternSyntaxException: Dangling meta character '?'

The problem here is that ? is a regex metacharacter, and to treat it as a literal question mark, you have to escape it:

    System.out.println("Hello???".replaceAll("\\?", "!"));
    // prints "Hello!!!"

Sometimes the string the pattern is an unknown, in which case you can use Pattern.quote:

    String unknown = "?";
    System.out.println(
        "Hello???".replaceAll(Pattern.quote(unknown), "!")
    ); // prints "Hello!!!"

To complicate matters slightly, the replacement string is actually also regex-based.

    System.out.println(
        "USD 10".replaceAll("USD", "dollar$")
    );
    // throws StringIndexOutOfBoundsException: index out of range: 7

To quote a replacement string, you use Matcher.quoteReplacement:

    System.out.println(
        "USD 10".replaceAll("USD", Matcher.quoteReplacement("dollar$"))
    ); // prints "dollar$ 10"

But what if I just want to do a simple no-regex replacement?

Then, to use replaceFirst, you have to quote both the pattern and the replacement strings:

import java.util.regex.Pattern;
import java.util.regex.Matcher;


String replaceFrom = ...;
String replaceTo = ...;

String before = ...;

String after = before.replaceFirst(
   Pattern.quote(replaceFrom), Matcher.quoteReplacement(replaceTo)
);

And if you need a replaceAll, then you just use the usual non-regex replace method instead:

String after = before.replace(replaceFrom, replaceTo);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.