ReplaceAll()

I have installed j2sdk1.4.l and the replaceAll() method in the String class allows me to replace a character with the string like this:
String str = "This is a test";
out.println(str.replaceAll(" ", "%20"));
I tested it on a local tomcat server and it worked and then I uploaded the file to the server, which is a Unix box. I can't figure out why I'm getting a no such method error when the replaceAll() method is supported. Originally I thought the server wasn't updated but it uses the same version as I do. Can anyone suggest anything or how do I overcome this?
thanks
gbilios

I'm just as familiar with URLEncoding as I am with the replaceAll()method. The problem with the URLEncoding is that it represents the spaces with the plus sign. Because I am dealing with hrefs, the spaces are represented by the '%20', and the replaceAll() method is more suitable. There is a strong possibility that Tomcat is refering to an earlier JRE, which doesn't support the replaceAll() method. The strangest thing is that j2sdk1.4.0_02 is installed on the server. I can use the replaceAll() in a standard app class and run but as a servlet I get the no such method error.
gbilios

Similar Messages

  • Regular expressions in String.replaceAll()

    Hi,
    I'm trying to implement automatic contextual links on a site.
    What I want is to parse a text (containing HTML tags) and replace every occurence of a word by a link.
    e.g., the text:
    "This is a test text for replacement".
    would be replaced by
    "This is a <a href="www.test.com">test</a> text for replacement".
    Now, obviously I don't want to just do a replaceAll("test", link) because it would also replace things like "contest".
    So I'm trying to detect everytime my keyword "test" is not surrounded by literals, which I can do with the regex \Wtest\W.
    But how can I use replaceAll() to make the application replace just the central bit and leave whatever non literal stuff is around ?
    Or maybe there is a better way of doing this ?
    Any idea will be welcome.
    Thanks

    Why are you makint it so complicated?
    public class Test {
         public static void main(String[] args) throws Exception {
              String text = "This is a test text for replacement";
              text = text.replaceAll(" (test) ", " <a href=\"www.test.com\">$1</a> ");
              System.out.println("After first pass " + text);
              text = text.replaceAll(" (test) ", " <a href=\"www.test.com\">$1</a> ");
              System.out.println("After second pass " + text);
    }But I agree with Sabre. You probably don't want to do several passes over the same data.
    Kaj

  • Problem with ReplaceALL-- Need Help

    I want to replace "&Acirc;" with "& n b s p;" ...
    Here is my code
    String content = "&Acirc; checking &Acirc;";
    content = content.replaceAll("\u00C2", "& n b s p;");
    or
    *content = content.replaceAll("[&Acirc;]", "& n b s p;");*
    *or*
    *content = content.replaceAll("&Acirc;", "& n b s p;");*
    All the above cases works fine in JAVA 1.6 but in JAVA 1.5 its not working so please help
    The only case working for me is the below one
    *content = content.replaceAll("^\\p{ASCII}","& n b s p;");*
    but this code will replace all the ASCII characters which will not solve my problem....

    Works fine on JRockit 1.5_015

  • Different results using Matcher.replaceAll on a literal depending on the Pattern compiled

    I would have expected that the results for all the following scenarios would have been the same:
    public class PatternMatcher {
        public static void main(String[] args) {
            Pattern p;
            Matcher m;
            // duplicates
            p = Pattern.compile("(.*)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("(.+)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // wtf
            p = Pattern.compile("(.*?)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // duplicates
            p = Pattern.compile("(.*+)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("^(.*)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // duplicates
            p = Pattern.compile("(.*)$");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("^(.*)$");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("(.(.*).)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
    But the results vary depending on the pattern compiled:
    (.*) : xyzxyz
    (.+) : xyz
    (.*?) : xyzaxyzbxyzcxyz
    (.*+) : xyzxyz
    ^(.*) : xyz
    (.*)$ : xyzxyz
    ^(.*)$ : xyz
    (.(.*).) : xyz
    Since all of the patterns have an all-encompassing capture group, but the replacement string does not have any group references, I was expecting that in every case the replacement string would simply be returned unchanged (so just "xyz").
    Have I uncovered a bug in the core library?  or am I misunderstanding how this should be working?

    jwenting wrote:
    And such is the case here.
    "You're doing it wrong, but I'm not going to tell you what it is you're doing wrong nah nah nah"
    That's the good thing about long lasting platforms such as Java - APIs become mature because they've been tested and re-tested by thousands of people for more than a decade. And thus when you go to use them and have to think "wtf", you can be almost certain you simply don't understand and meanies in forums can say so without having any ammunition to back up that accusation.

  • Using a local variable in regex portion of replaceAll(regex, replacement)

    While this works..
    output = output.replaceAll("(HED>|AUT>)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    I'd like the list of alternation values to be contained in a variable, for example:
    String nodeLIst = "HED>|AUT>";
    output = output.replaceAll("(nodeList)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    The extension of this would be so I can store this stuff in a db as a list and avoid compilation on change, but please don't let this muddy the waters... :)
    Any pointers are much appreciated. Links to specific reading material, etc. I've scoured Friedl's Mastering Regular Expressions to no avail. This approach is supported by some other regex engines I've used (perl, php, ORO?) but I'm new to Java.
    TIA,
    Mark

    I've scoured Friedl's Mastering Regular Expressions to no avail.Did you look on page 209? In the book, that code sample is labelled "Building Up a Regex Through Variables in Java". That should have been a clue. ^_^
    But seriously, you're probably thinking of the interpolated strings you find in scripting languages like Perl, PHP, Ruby, etc.. But that's a feature of the language itself, not the regex engine, and Java doesn't work that way. (The $1, $2, etc., in the replacement string are processed by the Matcher class, in a very limited imitation of Perl's variable interpolation).
    However, you can fake it pretty well with String's format() method:   String regex = String.format("(%s)(.*)(</\\1)", theAlternation);
      output = output.replaceAll(regex, "$1<![CDATA[$2]]>$3"); That way, you can easily escape the dynamic part, in case it might contain regex metacharacters:   String regex = String.format("(%s)(.*)(</\\1)", Pattern.quote(theAlternation));

  • String replaceall method

    public static String removeSpecialCharacters4JavaScript(String text)
              String result = null;
              if (text != null)
                  Hashtable forbidenEntities = PortalHelper.getTocForbidenEntities();
                   Enumeration keys = forbidenEntities.keys();
                   String key = null;
                   String value = null;
                   while (keys.hasMoreElements()) {
                        key = (String)keys.nextElement();
                        value = (String)forbidenEntities.get(key);
                        result = result.replaceAll("&"+key+";", value);
                   result = text.replaceAll("'","&#39;");
                   result = result.replaceAll("\"","&#34;");
              return result;
         i am getting problem at the replaceall method. plz suggest me here.
    thanks.

    Instead of iterating through the table and doing a replaceAll() for each entry, you should do one replaceAll(), looking up the replacement text in the table for each "hit". Elliott Hughes' Rewriter makes dynamic replacements like this easy to do.  private static Rewriter rewriter = new Rewriter("&(\\w+);|['\"]")
        public String replacement()
          if (group(1) != null)
            return (String)PortalHelper.getTocForbidenEntities().get(group(1));
          else if ("\"".equals(m.group(0))
            return "& quot;"; // remove the space
          else if ("'".equals(m.group(0))
            return "& apos;"; // remove the space
      public static String removeSpecialCharacters4JavaScript(String text)
        return rewriter.rewrite(text);
      }Just to be safe, in Rewriter.java replace the line            matcher.appendReplacement(result, replacement());with            matcher.appendReplacement(result, "");
                result.append(replacement());Otherwise you'll have problems whenever a dollar sign or backslash appears in the generated replacement text.

  • Can replaceAll do what I want?

    Hi
    I have a string "This is My string my way"
    This text will be in a button's text property.
    What I would like to do is add a html tag like the font tag to certain parts of the string to make it another color.
    The user will for instance provide the input "my" ,all input will be lowercase.
    Then it should add the following tag to the string : "This is <font>My</font> string <font>my</font> way"
    This should be done for all matching strings upper and lower case.
    I had a look at replaceAll, but it will replace only the exact string so if the input is lowercase it won't be replaced. I also need to retain the case of the "replaced" string so that "My" does not change to "<font>my</font>"
    Can replaceAll be used to do what I want?
    Some examples would be appreciated.
    Thanks

    The first argument to replaceAll() is a regular expression, which means you can do a lot more than just match case-insensitively, but here's how you would do that:  String str2 = str1.replaceAll("(?i)my", "<font>$0</font>");You might find these links useful:
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html
    http://www.regular-expressions.info/

  • Problem with the replaceAll method - please help

    When the source String contains some special characters like ' ? ' , ' ) ' , or ' ( ' etc, the replaceAll function doesn't has any effect on the source String.
    for example
    String k="images/mainpage7(sm)_01.jpg";
    String h=k.replaceAll("images/mainpage7(sm)_01.jpg","JoinNowBox_01.jpg");
    System.out.println(k);
    System.out.println(h);
    output:
    images/mainpage7(sm)_01.jpg
    images/mainpage7(sm)_01.jpg
    Can anybody tell me what to do?
    Thanks in advance
    Hristos Floros - Greece

    But what if I don�t know the values of all Strings?
    String a="images/mainpage7(sm)_01.jpg";
    String b="images/mainpage7(sm)_01.jpg";
    String c="images/mainpage7(sm)_01.jpg";
    String d=a.replaceAll(b,c);
    System.out.println(a);
    System.out.println(d);

  • String.replaceAll

    String line = "\"\\\"\""; // i.e. "\""
    line = line.replaceAll("\\\"", "@");
    I've expected the code above to change
    to
    but I get
    Could you please help me to understand why it is happening.
    P.S. I'd like to use the above technics in order to parse script commands like
    setText "this is a new text"
    where the second argument may contain excape characters (like \"). Therefore I'll replace \" by @ then find quoted string (using patterns) and then replace back @ by \" Do you have another suggestions to do this?
    Thak you in advance!

    String line = "\"\\\"\""; // i.e. "\""so line will be " \ " " (i used space so that it will more clear)
    line = line.replaceAll("\\\"", "@");and your are replacing " to @
    that's why you get @ \ @ @

  • Alternative for replaceAll()

    the replaceAll(String,String) is supported in java version 1.4 only and not in 1.3. can anyone suggest an alternative for the function in java 1.3?

    There's a regex package for 1.3 that the 1.4 stuff is based on. I think it's hosted at apache or sourceforge. Google for it.

  • Ah ha i have a java question about replaceAll

    for my find and replace component to do a replace all im simply saying
    text.replaceAll(find,replace)
    but if i try and find { and replace with } then it throws an exception because you need to escape the { (or the } which ever one)
    but because im passing them a parameter i cant just escape it.
    is there a simple way round this or would i have to have an array of all characters i need to escape?
    thanks

    hi
    i tried
    text.replaceAll("\Q"+f,"\Q"+r)
    and with \q
    but it returns an error
    findReplace.java [179:1] illegal escape character
    thats no good :(
    also sabre, how would u like me to elaborate more?
    i have a method that is passed 2 parameters, find and replace both strings
    then my replaceAll uses these 2 parameters
    replaceAll(find,replace)
    if the strings are "hello" & "byebye"
    then all hellos in the text are replaced by byebyes
    if the strings are "{" & "}" then it throws an exception

  • How to eliminate "\n" using String.replaceAll(str, str)

    I've noticed a few people having prob with replaceAll in the forum.
    Here's what I want to accomplish.
    I need to put the value received from HTML <textarea>, into just one line in a file.
    String sentence = "line1\nline2\nline3\nline4\n";
    System.out.println("before" + sentence);
    System.out.println("after" + sentence.replaceAll("\n", "\\n");The result looks like this.
    before= line1
    line2
    line3
    line4
    after= line1nline2nline3nline4n
    Notice that a backslash is missing.
    How can I get the original string with "\n" placed at the right place??
    Thanks a lot.
    Masako

    I've noticed a few people having prob with replaceAll
    in the forum.
    Here's what I want to accomplish.
    I need to put the value received from HTML <textarea>,
    into just one line in a file.
    String sentence = "line1\nline2\nline3\nline4\n";
    System.out.println("before" + sentence);
    System.out.println("after" + sentence.replaceAll("\n",
    "\\n");The result looks like this.
    before= line1
    line2
    line3
    line4
    after= line1nline2nline3nline4n
    Notice that a backslash is missing.
    How can I get the original string with "\n" placed at
    the right place??
    Thanks a lot.
    Masako
    I got the results you were looking for by doing it this way:
    sentence.replaceAll("\\n", "\\\\n");I'm a bit confused about this result, though. Like someone said earlier, i thought "\n" was a single character. Maybe it doesn't get evaluated into the newline character until it's displayed...?

  • ReplaceAll with file-path

    Hello,
    I get a filename from a textfield the user fills in.
    Then I want to do following:
    String in = "....kdfbkhsdbfkbfe #FILENAME# sdfsdkjfhskjdf...";
    String out = in.replaceAll("#FILENAME#",textField.getText());
    Problem: When user fills in something like E:\dir\temp\file then in out there is E:dirtempfile
    ??

    This is because the replacement string is not treated as a plain string. The replacement string may have references to the matching regular expression by using $number. \ is used to escape the $-sign when you want to use it as such.
    [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)]http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)
        "abcde".replaceAll("[bd]", "<$0>") = a<b>c<d>e
       "abcde".replaceAll("[bd]", "<\\$0>") = a<$0>c<$0>e
       "abcde".replaceAll("[bd]", "\\\\") = a\c\eSo you need to insert slashes in front of each \ and $. This can be done with    textField.getText().replaceAll("[\\\\$]", "\\\\$0");

  • ReplaceAll regexp and JavaScript

    I want to write a function that will escape special characters in a String so that they render correctly in JavaScript.
    For example, if a string contains a tab, I want the tab to be replaced by \t and so on for all the escape characters : \', \", \\, \b, \f, \n, \t and \r.
    Here is my function so far :
    public static String JSStringFormat(String value) {
        String result = "";
        if (value != null) {
            result = value;
            result = result.replaceAll("\'", "\\\\'");
            result = result.replaceAll("\b", "\\\\b");
            result = result.replaceAll("\f", "\\\\f");
            result = result.replaceAll("\n", "\\\\n");
            result = result.replaceAll("\t", "\\\\t");
            result = result.replaceAll("\r", "\\\\r");
        return result;
    }So far, this works... But I can't find the solution for \\ and \"... I've tried many things but nothing works...
    Anyone can help ?

    replaceAll("\"", "\\\""); // I thinkIt throws compilation error on this line itself. If
    you are using an IDE, it wont allow you to go further
    with that line.
    replaceAll("\\\\", "\\\\\\\\"); // I think.
    I had a slight error in the quote one the replacement string needed two more quotes. This works:         String str = "\\a \"xyz\" \\ b";
            System.out.println(str);
            //System.out.println(str.replaceAll("\\" , "\\\\\\"));
            System.out.println(str.replaceAll("\"", "\\\\\""));
            System.out.println(str.replaceAll("\\\\", "\\\\\\\\"));Your line (commented above) gives Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
    ^
    regEx is particular about special characters like $
    and \.Yes, I know.
    So when you are using replaceAll, you have to
    be careful with regex, and replace them. For example,
    if you have a $ to be replaced, you have to replace
    it the following way.
    str.replaceAll("\\$", "\\\\\\$");Yes.
    >
    so, instead of directly using the $, you have to use
    "\\" that tells the regEx, yes this is a special
    character and treat it normally, like any other
    character.Yes.
    Along those same lines, like I said, you need \\ to get a single \ in a Java String. Then, if you want a literal \ in the regex, you need to provide the regex compiler with \\, which means your Java String literal must be \\\\.

  • String.replaceAll strange behavior...

    I have found strange behavior of String.replaceAll method:
    "aaaabaaaa".replaceAll("b","a"); // working fine
    "aaaabaaaa".replaceAll("b","a${"); // throws an exceptionThat could be probably a bug?
    p.s. using jdk_1.6.0_12-b04

    Welcome to the Sun forums.
    >
    "aaaabaaaa".replaceAll("b","a${"); // throws an exception
    Please always copy/paste the [exact error message|http://pscode.org/javafaq.html#exact]. We do not have crystal ball, and cannot see the output on your PC.
    >
    That could be probably a bug? >(chuckle) It has more to do with special characters in Strings, that need to be escaped. I am not up on the fine details, but try this code.
    import javax.swing.*;
    class TestStringReplace {
      public static void main(String[] args) {
        String result = "aaaabaaaa".replaceAll("b","c"); // working fine
        JOptionPane.showMessageDialog(null, result);
        result = "aaaabaaaa".replaceAll("b","c\\${"); // chars escaped
        JOptionPane.showMessageDialog(null, result);
    }

  • ReplaceAll not working for trademark

    Sorry, my last post was unclear due to the html in the browser changing it.
    this.alertTextSuffix = replaceAll("�", "ampersand trade;");
    The � symbol is not recognized by java and I am getting a replace.
    What do I need to do?

    Heres an idea. Why dont you check your String encoding?
    http://mindprod.com/jgloss/encoding.html
    And then, use its unicode (or whatever) number in the regex instead
    of the actual symbol.
    Also, different fonts might have symbols in different places.
    In Windows:
    Start > All Programs > Accessories > System Tools > Char Map
    For me: TM = U+2122 / ALT+0153 in Arial

Maybe you are looking for

  • Installing the 3 Port Lacie Fire Wire PCI Card

    Hello all After acquiring 2 external Lacie Fire Wire HD's, and wanting to have the ability to connect my Camcorder as well, (without dazzie chaining everything), I decided to get the Lacie 3 Port Fire Wire PCI Card: http://www.lacie.com/products/prod

  • How to get the profile name

    I did not know how to get the profile name in photoshop file using javascript? Kindly help me.

  • Hot to set the Non-alphanumeric characters attribute?

    Hello, I'm developing an asp.net application using the oracle membership provider. I have installed the databse objects in an Oracle 9i and when I try to create a new user, It always asks me to consider at least 1 Non-alphanumeric character in the pa

  • Safari Keeps Forgetting Settings

    Safari keeps forgetting the setting after I close it down and open it up.It goes back around to the Safari Apple Welcome Page.Reinstall safari but with no joy at all. Anyone Help

  • How to resolve TNS-12537: TNS:connection closed

    sqlnet.ora ========== # This file is actually generated by netca. But if customers choose to # install "Software Only", this file wont exist and without the native # authentication, they will not be able to connect to the database on NT. SQLNET.AUTHE