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

Similar Messages

  • 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

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

  • 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

  • String.replaceAll bottleneck

    Hi All,
    I have written a method to make a string "safe" for xml, by encoding characters that need to be replaced.
    It works just fine using String.replaceAll as below, but when i profile the app i see that it is a performance bottleneck.
    I can see that it is creating a lot of Strings so this is part of the problem.
    From reading through the forum I can see regexs used frequently for this type of problem, but it seems that they will not be more efficient than my existing approach.
    I see that StringBuffer has a replace method but i'm not sure that it is a good fit for my problem?
    Can anybody suggest a more efficient solution?
    Your help is much appreciated!
    emhart
    Here's my existing method:
    public static String makeSafeForXML(String str)
    String result = str;
    result = result.replaceAll("&", "&");
    result = result .replaceAll(">", ">");
    result = result .replaceAll("<", "<");
    result = result .replaceAll("'", "&apos;");
    result = result .replaceAll("\"", """);
    return result ;
    }

    That method doesn't make any sense to me:
    replacing strings with the same exact string?
    also the last one isn't correct, maybe missing a \ ?
    Also, you do realize that the replaceAll method uses the first argument as a regex to match patterns in the string?
    My apologies if I'm missing something.
    But if this really is what you want, then maybe this is faster (I haven't measured any times though):public static String makeSafeForXML2(String str)
        StringBuilder sb = new StringBuilder(str);
        for (int i = 0; i < sb.length(); i++) {
            switch (sb.charAt(i)) {
                case '&':
                    sb.replace(i, i + 1, "&");
                    break;
                case '>':
                    sb.replace(i, i + 1, ">");
                    break;
                case '<':
                    sb.replace(i, i + 1, "<");
                    break;
                case '\'':
                    sb.replace(i, i + 1, "'");
                    break;
                case '"':
                    sb.replace(i, i + 1, "\"");
                    break;
        return sb.toString();
    }

  • Bug in String.replaceAll()

    Hi folks,
    Have anybody try to do the following with String.replaceAll()?
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\");
    It will throw IndexOutOfBoundException.
    Billy Ng

    I'm not sure that's a bug, it's just the behavior of the underlying regex processor.
    Regardless, to get the effect you want, try:
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\\\");

  • Matcher vs. String.replaceAll

    I have been experiencing a problem attempting to use an expression such as:
    s = s.replaceAll("PATTERN","REPLACEMENT");
    to replace certain regular expressions in a document. When using the Matcher to replace Strings as follows there is no problem, but using the same pattern with String.replaceAll doesn't seem to perform the replacement.
    Pattern pattern = Pattern.compile("PATTERN",Pattern.DOTALL);
    Matcher matcher = pattern.matcher(s);
    s = matcher.replaceAll("REPLACEMENT");
    The only thing I can think of is that the Pattern.DOTALL options allows the match to take succeed, where it wouldn't otherwise. Therefore I was wondering if there an equivalent for the String.replaceAll method perhaps? Any ideas?
    Thanks very much,
    Ross Butler

    I'm having trouble believing that PATTERN and REPLACEMENT are the real string you're using, but it's probably not important, since it sounds like you probably diagnosed the problem yourself.
    According to the Javadocs, replaceAll gives the same result as Pattern.compile(regex).matcher(str).replaceAll(repl), but obviously that wouldn't necessarily be true if you add extra parameters somewhere in there, so I would say that replaceAll is more of a convenience method that you use when you don't need any extra parameters.
    However, if you need to use DOTALL or something else similar, you'll need the longer way using Matcher.
    That shouldn't stop you from writing your own convenience method, though. :)

  • String.replaceAll problem

    I need to replace a single quote ( ' ) in a string with two single quotes. I am trying to use String.replaceAll method but it does not work. I guess my regular expression is not correct. I have tried several combinations already.
    text.replaceAll(".'.","''");
    text.replaceAll("'","''");
    text.replaceAll("\\'","''"); None of them have worked. It does not change the text as I'd like it to.

    It's been at least a week since I've posted this:
    Since regex patterns are involved, you can use the simpler replace method:
    str = str.replace("'", "''");By the way, I hope you not doing this to insert text into a database!

  • Trouble with String.replaceAll( )

    Hi,
    I have a string which contains instances of the backslash character followed by the double quote character and I'd like to replace those two characters with just a double quote. Or to put it slightly differently, I'd like to remove all backslash characters which precede double quotes. It seems like this should be straight-forward, but for some reason, I'm not getting the results I expect.
    Here is my code:
              String s1 = "Foo\\\"Bar";
              System.out.println("s1 = " + s1);
              int len = s1.length( );
              System.out.println("s1.length( ) = " + len);
              String s2 = s1.replaceAll("\\\"", "\"");
              System.out.println("s2 = " + s2);
              len = s2.length( );
              System.out.println("s2.length( ) = " + len);
    And here is the corresponding output:
    s1 = Foo\"Bar
    s1.length( ) = 8
    s2 = Foo\"Bar
    s2.length( ) = 8
    So, the string isn't being changed at all. What am I doing wrong? Thanks in advance for any replies.
    -ts1971

    Melanie_Green wrote:
    string.replaceAll()Takes two arguments, the first is a regular expression, the second is a String. Regular expressions have their own syntax compared to Strings, to match a single black slash in a regular expression you must write "\\\\".
    MelJust a little nit-pick: the second parameter is not a plain String but a "regex replacement String". In it, the following characters have a special meaning and therefore need to be escaped if you'd like to use them as literals:
    $    // used for match-group interpolation
    \    // used to escape '$' and '\' itself

  • 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

  • How to use String.replaceAll(String regex, String replacement)?

    hi,
    I'd like to use the String.replaceAll call to replace all occurrences of a pattern in a string with a string inputted from the user.
    The problem is that replaceAll seems process the replacement string first. For example, the code below won't work
    public class StringTest {
         public static void main(String [] arg) throws Exception {
              String input = "oooIoooIooo";
              input=input.replaceAll("I","\\");
              System.out.println(input);
    }So the only option seems to be to manually process the user input string into a form that can be accepted by String.replaceAll?
    The only thing I can find from looking through the API is that you'd need to convert each backslash to a double-backslash?
    is this the right thing to be doing?
    thanks,
    asjf

    just to clarify, at the moment I think the solution is to do this
    public class StringTest {
         public static void main(String [] arg) throws Exception {
              String input = "oooIoooIooo";
              String raw = "\\";
              input=input.replaceAll("I",raw.replaceAll("\\\\","\\\\\\\\"));
              System.out.println(input);
    }

  • ReplaceAll / regexp / escaping a string

    Hi, I have a question about escaping a string for use with replaceAll. My objective is to replace all instances of string1 with string2 so I have been doing so using replaceAll. This works well however with it relying on regexp's I have some questions about escaping.
    I want to, for example, replace [%PARAM%] with '100%' however this starts to get in to the murky (to me) worlf of regular expressions. After some testing I realize I have lots of characters that are important to the regexp and I can avoid problems by escaping them like this:
    \\[\\%PARAM\\%\\] with '100\\%'
    This works however the values will be parsed out of strings the user enters so clearly I don't want them to have to add the escape characters, is there a way I can:
    a) Tell it to ignore special characters so it is treated like a basic searcha nd replace or
    b) Autmatically escape any problematic characters in the string before calling replaceAll?
    If there is another approach you would recommend I'd be very interested to hear it too.
    Thanks in advance,
    Chris.

    Don't get me started on the evils of writing Java inside JSP!
    Anyway, if you look at the documentation I helpfully linked for you, you'll see that the replace method that can take two Strings (two CharSequences to be precise) versus just two chars was introduced in version 1.5, so you must be using an older compiler.
    You should consider upgrading to 1.6. Even 1.5, let alone the version you must be using, is in its Java Technology End of Life (EOL) transition period.
    [http://java.sun.com/javase/downloads/index_jdk5.jsp]

  • 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

Maybe you are looking for

  • Windows – but Which? (What to install on Mac Pro Quad Core?)

    First, apologies in advance if this seems like repetition of a recent topic, but I read through the recent "Vista vs XP" thread and it didn't quite answer my questions. Basically, I'm planning on buying a Mac Pro "Quad Core" 2.8 and installing Boot C

  • Account Determination error while MIRO cancellation

    Hi Masters       While cancelling the invoice document in MR8M we get the following error Account Determination 1000 DIF not possible The transaction key DIF refers MM Small Differences. While posting the above MIRO document the users has given Rs. 7

  • Delete and renameto not working in java

    guys, i have written a java program that reads file1 into temp file and finally writes into another file. program is working fine with no errors, it even reported that the file is deleted. But actually the file was not deleted and renameto was never

  • IDES server Password reset link --- Not Opening

    Dear Concern ,                                  IDES server daily password reset link is not opening from yesterday. Kindly let know when this might be corrected. Best Regards Keerthan Kumar

  • Having trouble getting "Set action to take when logon hours expire" to work - Windows Server 2012

    I have a Windows Server 2012 server that allows remote desktop users (sessions are hosted on the server itself). I'm trying to enforce logon hours for these remote desktop users. I have specified logon hours for a user and confirmed that they work--t