String.replaceAll(String,"\\")

Hello, i tried this here but strangely it does not work.
The machine gives an ArrayIndexOutOfBoundsException...
Seems the method does not run with the "\" character. What did i do wrong?
public class Zeichen {
     public static void main(String[] args) {
          Zeichen ch = new Zeichen();
     public Zeichen() {
          String str = "this";
          str=str.replaceAll("i","\\");
          System.out.println(str);
}

The method header for the String.replaceAll() that you are trying to use is as follows
public String replaceAll(String regex,
                         String replacement)[\code]
The string "i" that you are entering is not a regular expression, which are listed at http://java.sun.com/j2se/1.4/docs/api/java/util/regex/Pattern.html#sum

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

  • 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.

  • 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 @ \ @ @

  • 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...?

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

  • Problem in String.replaceAll please help

    String ash = "XXX";
    String ch = ash.replaceAll("X","$");
    while executing the above code i am getting an exception
    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)
    please help me
    baiju

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=607145

  • Using backreferences in String.replaceAll()

    hi, i have a string (retrieved from a JTextField), that i'd like to run through a regex Pattern, but first I'd need to escape ANY non-alphanumeric characters. i thought i could use the String class' replaceAll method, to replace each matching character with a backslash, plus \1 (a backreference to the matching character), but \1 in the second (replacement) string doesnt seem to return the matching character from the first (regex) string....how would i determine then, which character matched the pattern?
    for instance, i grab the string "full[win32]" from a JTextField, and i want to escape anything that isnt a letter or number, and end up with "full\[win32\]".

    Okay, this seems to work. You use the $ sign, not the \, in the replacement string to refer to a capturing group. And you want the replacement string to have \\$1. You need \\ so that the \ escapes the next \ and becomes a literal \ in the output. If it was a single \, then it would escape the $, and $1 wouldn't be interpreted as a reference to a capturing group. It would be taken as the literal $ followed by 1.
    Finally, since \ is an escape char in Java String literals, it has to be escaped by \ so you end up with \\\\$1, which gets fed to the Matcher as \\$1, which means "literal \ followed by capturing group 1".
    newStr = oldStr.replaceAll("([^\\p{Alnum}])", "\\\\$1");

  • .. in String.replaceAll / regexp

    Hello,
    I have now tried and read ages but cannot get the solution (having a bit experience in Perl regexpt also...). I simply want to replace two sequencing full stops within a string to null, like this:
    str = str.replaceAll("..", "");
    However, I cannot manage to, . having a special meaning in regexps. I tried things like \Q..\E or \.\. and so on, but it never works or even compiles. I think I have not understood some fundamental stuff... :-)
    Thanks for any help!
    Greetings, Timo

    Hello Legosa,
    That did it! However, I really do not understand, cos backslash being an escape char, I would have expected this output:
    \\.\\. => \.\.
    The first backslash being the escaper for the second. Well...
    But it works, big thanks again,
    Greetings, Timo

  • Regular Expression Fails String replaceAll

    I am trying to use regular expressions to replace double backslashes in a string with a single backslash character. I am using version 1.4.2 SDK. Upon invoking the replaceAll method I get a stack trace. Does this look like a bug to anyone?
    String s = "text\\\\";  //this results in a string value of 'text\\'
    String regex = "\\\\{2}";  //this will match 2 backslash characters
    String backslash = "\\";
    s.replaceAll(regex,backslash); java.lang.StringIndexOutOfBoundsException: String index out of range: 1
         at java.lang.String.charAt(String.java:444)
         at java.util.regex.Matcher.appendReplacement(Matcher.java:551)
         at java.util.regex.Matcher.replaceAll(Matcher.java:661)
         at java.lang.String.replaceAll(String.java:1663)
         at com.msdw.fid.fitradelinx.am.client.CommandReader.read(CommandReader.java:55)
         at com.msdw.fid.fitradelinx.am.client.CommandReader.main(CommandReader.java:81)
    Exception in thread "main"

    Skinning the cat -
    public class Fred12
        public static void main(String[] args)
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "[\\\\]{2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(\\\\){2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(?:\\\\){2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(?:\\\\)+";  //this will match 2 or more backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "\\\\\\\\";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
    }

  • String.replaceAll() don't works!!!

    Hi all,
    I want to use replaceAll(string,string), but it don't works.
    Here is an example:
    String str = "This is the 'repl' I want replace and a second 'repl'";
    String regex = "repl";
    String replace = "new string";
    str.replaceAll(regex,replace);
    //Result should be: str => "This is the 'new string' I want replace and a second 'new string'"
    The Result is the same string I had before, absolutely no changes!!!
    Can someone tell me whats wrong????
    Thanx for your help.
    cya JayR

    str.replaceAll(regex,replace);
    //Result should be: str => "This is the 'new string' I want replace and a second 'new string'"As the others said, the value of str itself will not change. That's not Strings work. They're immutable (meaning they will never change value once instantiated). If you want str to have the new value, you'll need to do:str = str.replaceAll(regex,replace); And by the way... "This is the 'repl' I want replace and a second 'repl'" will not end up being "This is the 'new string' I want replace and a second 'new string'", actually, it will be "This is the 'new string' I want new stringace and a second 'new string'". The "repl" in the word "replace" will be replaced by "new string" as well.

  • String.replaceAll doesn't work

    Hi,
    I hope this is the correct forum to post about this problem. It's not a compiler error, it rather seems to be an interpreter or a logical error.
    Please consider this test program I wrote to clarify the problem.
    public class Test {
        public static void main( String args[]) {
         String someString = "Hello $place!";
         System.out.println( someString.replaceAll( "place", "world"));
         System.out.println( someString.replaceAll( "$place", "world"));
    }The method String.replaceAll should replace all occurences of regex with replacement.
    Also see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
    So, one should think my test program would have the following output:
    Hello $world!
    Hello world!Alas, it isn't so. The program outputs the following using SDK 1.2.4:
    Hello $world!
    Hello $place!The String.replaceAll method doesn't seem to replace occurences if they are preceeded of "$". Or am I just missing something?

    The String.replaceAll method doesn't seem to replace
    occurences if they are preceeded of "$". Or am I just
    missing something?You're right. The method replaceAll is expecting a [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html]regular expression. See there how to escape special control chars like $ which means 'end of line'.

  • Problem trying to use replaceAll with url string

    Can anyone give me some quick advice on how to replace part of a url? I'm trying replaceAll but I'm getting errors. My code is below. Thanks.
    String value = http://localhost:8280/portal/templates/page/library.jsp?foldId=libfold245696
    String hostName = "192.168.0.1";
    value = value.replaceAll("localhost",hostName);I want to replace "localhost" with the ip address.

    Here's the replaceAll version:
    package com.cellexchange.util;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    import java.util.Properties;
    * Created on Nov 3, 2005
    public class UpdateExternalLinks {
        private String hostName;
        private String fileName = "/server/fvm/conf/ExternalLinks.properties";
        private static final String pattern = "localhost";
        private Properties properties;
        public UpdateExternalLinks(String hostName,String jBossHome){
            hostName = hostName;
            System.out.println("hostName: " + hostName);
            fileName = jBossHome + fileName;
            readPropertiesFile();
        public static void main(String[] args) {
            if(args.length == 0) {
                System.err.println("Usage: UpdateExternalLinks %HOST_NAME% %JBOSS_HOME%");
                System.exit(1);
            else {
                new UpdateExternalLinks(args[0],args[1]);
        public void readPropertiesFile() {
            try {
                properties = new Properties();
                properties.load(new FileInputStream(fileName));
                Enumeration propertyNames = properties.propertyNames();
                while(propertyNames.hasMoreElements()) {
                    String key = (String)propertyNames.nextElement();
                    String value = (String)properties.getProperty(key);
                    System.out.println("key: " + key);
                    System.out.println("value: " + value);
                    String newValue = value.replaceAll(pattern,hostName);
                    System.out.println("newValue: " + newValue);
                    //properties.setProperty(key,newValue);
               // writePropertiesFile(properties);
            } catch (IOException e) {
                System.err.println("Problem reading properties file");
        public void writePropertiesFile(Properties properties) {
            try {
                properties.store(new FileOutputStream(fileName), null);
            } catch (IOException e) {
                System.err.println("Problem writing properties file");
    }

  • PatternSyntaxException when calling String.replaceAll in multithreaded app

    Dear,
    Someone ever encountered or knows of problems when invoking String.replaceAll in a multithreaded application (JDK 1.4.2)?
    I have an application that invokes replaceAll on a String and that runs just fine when only a single thread is active, but once multiple threads execute the same code, each on its own String instance, the following stack is produced (more often than not).
    java.util.regex.PatternSyntaxException: Unknown character category {Digit} near index 9
    ^\p{Digit}
    ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.familyError(Unknown Source)
    at java.util.regex.Pattern.retrieveCategoryNode(Unknown Source)
    at java.util.regex.Pattern.family(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    The 1.4.2 source code seems to use a static HashMap (java.util.regex.Pattern#retrieveCategoryNode) to store some read only data, but it looks like the initialization of that HashMap in an multi threaded environment is not 'locked'. Could that be the/an issue? Anybody any thoughts?
    Thanks,
    Peter

    I ran peter's program on a hyperthreaded Intel P4 box and XP Pro. XP reports that there are 2 processors.
    I used 1.4.2_06 and 1.5.0_01, with both -client and -server options.
    The program was run with numThreads 10 and loadPattern 0 and 1.
    The program was run 50 times for each of the configurations. Only one resulted in failures, as follows:
    Java version     cli/svr          Pgm Parms   # Failures      
    1.5.0_01     -client          10, 0          0
                        10, 1          0
              -server          10, 0          0
                        10, 1          0
    1.4.2_06     -client          10, 0          10
                        10, 1          0
              -server          10, 0          0
                        10, 1          0
    Of the 10 failures, 1 reported 3 errors, 2 reported 2 errors, and 7 reported 1 error.
    The triple-error report is below:
    "C:\Program Files\Java\jdk1.4.2_06\bin\java.exe" -client PatternProblem 10 0
    Thread-7:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Thread-5:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Thread-3:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Note that this wording is not the same as peter encountered. The thread number varied,
    apparently randomly, from 0 to 8

  • Removing \n and leading spaces with String.replaceAll()

    I am trying to format a large XML string that contains carriage returns and lines with leading spaces. Something like this (pseudo example)...
    s: "<a>
    ��<b>some text</b>
    ��<c>
    ����<d>more text</d>
    ��</c>
    </a>"When i am done, i want it to look like this...
    s: "<a><b>some text</b><c><d>more text</d></c></a>"I have tried using replaceAll() in this way....
      s = s.replaceAll("^\\s+","");// to remove leading spaces
      s = s.replaceAll("\\n","");// to remove carriage returnsHowever, I am not getting the results I expect. In fact, the entire string seems to simply turn into all whitespace....
    s: "                                           "My question is: Is there an easier way? (or at least a way that works?)

    try this:
    public String transformXML(String s) {
        s = s.replace("^\\s+", "");
        s = s.replace("\\s+$", "");
        s = s.replace("\\s+", " ");
        s = s.replace("\\s*<\\s*([^<>]*?)\\s*>\\s*", "<$1>");
        return s;
    }which would transform your example expression from:
    <a>
    <b>some text</b>
    <c>
    <d>more text</d>
    </c>
    </a>
    to probably what you want:
    <a><b>some text</b><c><d>more text</d></c></a>
    Hope this helps~
    Alex Lam S.L.

  • String.replaceAll howto use it ?

    Hi everyone I want to replace newlines in a String with spaces. I though the use of replaceAll would be great but am having no luck with it at all.
    String commentString "hello\nhello\n";
    commentString.replaceAll("\\\n", " ");
    I have no idea why this is not working, any help appreciated.
    Cheers
    Dan

    public class Test {
        public static void main (String[] parameters) {
            System.out.println ("a\nb".replaceAll ("\\n", " "));
    }Kind regards,
      Levi

Maybe you are looking for

  • How do I enable 'iCloud Status' view in iTunes 11.1?

    Previously Match users were able to activate 'iCloud Status' view in the music library columns. This feature would indicate if a song were uploaded / matched / etc. After updating to the iTunes 11.1, this feature seems to be missing or moved to a sep

  • Lion and Amazon

    Since upgrading to Lion I'm having problems making purchases from Amazon UK. Once the order is completed it asks me again for the delivery address. Once I've done so it restarts the ordering process from the beginning. Once completed, it again asks f

  • Movie Sync Issue on iPhone5, iOS6

    I am new to the Apple Support Communities and first of all I want to say hello to everybody. But I have a huge problem with syncing HD movies to my device. Background: I have a small Bluray collection, which I copied to my HDD to convert them using H

  • Best way to back up 5.0.4 projects

    I just got the crossgrade and want to update my system. I have two big projects created in 5.0.4 but need to update for another project which requires 5.1 to be installed. Can someone tell me the best way for me to save and backup my 2 projects just

  • Standard application log modification

    Hello all, I need help. I need to modify the standard application log,I have to change the header text(means we need to extend the header data). how can i processed Please help. Thanks & Regards, Naren.