[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

String replaceAll method

Posted on 2006-06-04
29
Medium Priority
?
239 Views
Last Modified: 2012-05-05
I have a string with lots of braces ")" and "(".
Eg

String s = "FIELD ( .......)";

String toReplace = "Field (" ;
I want some part to be replaced by another string.

String replaceWith = "F (";

When I try to use the replaceAll function, I get no result.

s = s.replaceAll(toReplace , replaceWith );

It looks like it is because of the "(" in the string. Can someone please help me resolve this?
thanks
0
Comment
Question by:thomas908
  • 9
  • 8
  • 8
  • +1
29 Comments
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16826908
use this:

toReplace = "Field \\(";
0
 
LVL 8

Author Comment

by:thomas908
ID: 16826926
Thanks for the quick response.
I am getting that String by calling some predefined methods (which I can't change).
It's something like

toReplace = new SomeClass().someMethod();

This gives me a string. I want to change some values in that string. Please let me know what should i do.
thanks
0
 
LVL 14

Assisted Solution

by:hoomanv
hoomanv earned 200 total points
ID: 16826932
toReplace = toReplace.replaceAll("\\(", "\\\\(");
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 14

Expert Comment

by:StillUnAware
ID: 16826940
You must escape special characters in the toReplace string, so that the regex interpret them right. You could try this:

toReplace = new SomeClass().someMethod().replaceAll("\\(", "\\(");
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16826943
hoomanv supplied answer is the correct one, ignore my replace
0
 
LVL 8

Author Comment

by:thomas908
ID: 16826952
Thanks for replying.
But both these Strings I am getting by calling some methods.

So, I am getting these values in variables. What should I do in this case.
I'll have to use replaceAll to first replace "(" with "\\(" ?
0
 
LVL 8

Author Comment

by:thomas908
ID: 16826956
Sorry, misunderstood the answer...
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16826963
Forget that, here is a cleaner solution. Leave everything as is, and change only the toReplace like that:

String s = "FIELD ( .......)";
String toReplace = "\\Q"+(new SomeClass().someMethod())+"\\E"; // quote all the search string
String replaceWith = "F (";
s = s.replaceAll(toReplace , replaceWith );
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16826964
> I'll have to use replaceAll to first replace "(" with "\\(" ?
both for toReplace and replaceWith

0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16826971
I suggest You read about the regex. It's all about the string matching and replacing, and the String.replaceAll(...) makes use of it:

java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16826989
without the need to escape

"FIELD ( .......)".replace("(", "F (");
results in "FIELD F ( .......)"
0
 
LVL 8

Author Comment

by:thomas908
ID: 16827005
>> Forget that, here is a cleaner solution. Leave everything as is, and change only the toReplace like that:

Not working. Its not giving any results.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16827017
Can you give us a *concrete* example of the String that you want to find, together with one you want to replace by?
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16827018
Odd, this works for me:

    String s = "FIELD ( .......)";
    String toReplace = "\\Q"+"FIELD ("+"\\E";
    String replaceWith = "F (";
    s = s.replaceAll(toReplace , replaceWith );
    System.out.println(s);

and I get the result: F ( .......)

Can You give some more examples of strings toReplace and replaceWith?
0
 
LVL 8

Author Comment

by:thomas908
ID: 16827037
>> Can you give us a *concrete* example of the String that you want to find, together with one you want to replace by?

String s = "( AND (  FIELD (NUMBER1 IN-FULLTEXT 'tuty5' ) ,  OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE1 >= 10-10-2005 ),FIELD (DATE3 >= 10-10-2005 )) , FIELD(TYPE IN ( '1', '2' )),FIELD(D IN '000000000'))  )"; //comes from a method call

String toReplace = "FIELD (DATE >= 10-10-2005 )" ; //comes from a method call

String replaceWith = "OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE2 >= 10-10-2005 ))"; ////comes from a method call

String s needs to be modified and toReplace needs to be replaced with text from replaceWith.

thanks
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16827039
In the worst case, it may happen that the toReplace string somewhere at the begining has a combination of characters "\\E". In that case the PatternSyntaxException should be thrown, which didn't happen.

Which Java version are You using? Maybe there are some incompatibilities.
0
 
LVL 8

Author Comment

by:thomas908
ID: 16827043
>>Which Java version are You using? Maybe there are some incompatibilities.
J2SE 1.4
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16827046
use replace instead of reaplaceAll
0
 
LVL 8

Author Comment

by:thomas908
ID: 16827050
>> use replace instead of reaplaceAll
It gives an error
replace(char,char) in java.lang.String cannot be applied to (java.lang.String,java.lang.String)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16827053
String toReplace = "FIELD (DATE >= 10-10-2005 )" ; //comes from a method call
toReplace = toReplace.replaceAll("\\(", "\\\\");
String replaceWith = "OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE2 >= 10-10-2005 ))";
replaceWith = replaceWith.replaceAll("\\(", "\\\\");
replaceOn = replaceOn.replaceAll(toReplace, replaceWith);
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16827055
aah replace(String, String) has been added since 1.5
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16827056
Sorry - typo

>>replaceAll("\\(", "\\\\");

should be

replaceAll("\\(", "\\\\(");
0
 
LVL 14

Accepted Solution

by:
StillUnAware earned 300 total points
ID: 16827057
This worked for me again:

    String s = "( AND (  FIELD (NUMBER1 IN-FULLTEXT 'tuty5' ) ,  OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE1 >= 10-10-2005 ),FIELD (DATE3 >= 10-10-2005 )) , FIELD(TYPE IN ( '1', '2' )),FIELD(D IN '000000000'))  )"; //comes from a method call
    String toReplace = "\\Q"+"FIELD (DATE >= 10-10-2005 )"+"\\E" ; //comes from a method call
    String replaceWith = "OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE2 >= 10-10-2005 ))"; ////comes from a method call    s = s.replaceAll(toReplace , replaceWith );
    System.out.println(s.replaceAll(toReplace, replaceWith));
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16827063
closing parenthesis should be escaped too
toReplace = toReplace.replaceAll("\\)", "\\\\)");
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16827068
>>closing parenthesis should be escaped too

True
0
 
LVL 8

Author Comment

by:thomas908
ID: 16827076
>> This worked for me again:
Yes, it works. I was making a mistaking
Thanks a lot everyone...
0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16827077
Standard Way

import java.util.regex.*;

String result = Pattern.compile(toReplace, Pattern.LITERAL).matcher(s).replaceAll(Matcher.quoteReplacement(replaceWith));
            System.out.println(result);

0
 
LVL 14

Expert Comment

by:hoomanv
ID: 16827080
my last comment is the best way though :)
0
 
LVL 14

Expert Comment

by:StillUnAware
ID: 16827110
Thanks for accepting, I have another solution, maybe a little bit faster:

    String s = "( AND (  FIELD (NUMBER1 IN-FULLTEXT 'tuty5' ) ,  OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE1 >= 10-10-2005 ),FIELD (DATE3 >= 10-10-2005 )) , FIELD(TYPE IN ( '1', '2' )),FIELD(D IN '000000000'))  )"; //comes from a method call
    String toReplace = "FIELD (DATE >= 10-10-2005 )"; //comes from a method call
    String replaceWith = "OR( FIELD (DATE >= 10-10-2005 ), FIELD (DATE2 >= 10-10-2005 ))"; ////comes from a method call    s = s.replaceAll(toReplace , replaceWith );
    int pos = 0;
    while((pos = s.indexOf(toReplace, pos)) != -1) {
      s = s.substring(0, pos) + replaceWith + s.substring(pos + toReplace.length());
      pos = pos + replaceWith.length();
    }
    System.out.println(s);

this does not use regex and although it may be optimized even more.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month19 days, 11 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question