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!

Similar Messages

  • 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

  • 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(regex, with what);

    im looking for a way to replace specific instances of words in a string
    for instance, replace %URL% with a specific URL in a string. the problem is i cant get replace all to recognize %URL% without using something like \\p{symbol} or something like that with %URL%
    i've tried
    "%URL%"
    "\%URL\%"
    but none work
    help please :)
    thanks

    String str = "this address %URL% is fake";
    String addr = "http://some.name.com";
    String result = str.replaceAll("%URL%",
    addr);produces
    this address http://some.name.com is fake
    So the % is not a special character...
    to OP: If it isn't working, read the error more closely. Post it here if you still have problems.

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

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

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

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

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

  • 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("/", "\\\\");

  • 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

  • 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 how far can you take it?

    Hi,
    I want to do 2 (or 3) simple string conversions like this:
    1. in: "CustomerOrderHistory" out: "customer_order_history"
    2. in: "customer_order_history " out: either "CustomerOrderHistory" or "customerOrderHistory" (either ok)
    Actually number 2 is no problem, I did it like this:
    public static String mixedCaseToCaseInsensitiveLower (String input) {
         return input.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();           
    }No problem works fine, but now I'm wondering if it's possible to implement case 1 in a one liner like that.
    Of course, I I can see how I could code it with a specific routine, but I'd like to know if the replaceAll method can do it for me.
    So far I have this:
    return input.toLowerCase().replaceAll("((_)([a-z]))", "$1")This just removes any underscores that occur before a lower case character, but I don't see any way to tell it that the character after the underscore, ie "$1" should be upper cased.
    It may be that I'm asking too much, or it may be that I've missed something... tell me what you think,
    Thanks
    Iain

    You're asking too much. :/
    You have to process the replacement text before it gets inserted into the result string, which means you can't use replaceAll(). You can, however, do it he long way, using Matcher's appendReplacement() and appendTail() methods:  private static Pattern p = Pattern.compile("(?:$|_)([a-z])");
      // to leave the first letter lowercase, use "_[a-z]"
      public static String toCamelCase(String input)
        Matcher m = p.matcher(input);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          m.appendReplacement(sb, m.group(1).toUppercase());
        m.appendTail(sb);
        return sb.toString();
      }Of course, with about the same amount of effort, you do the same thing with indexOf(), charAt(), and a for loop. Now, if we could combine Matcher with the new Formatter (sprintf) class, we could really have some fun...

Maybe you are looking for

  • Is there a way to open an apple store account without adding card info?

    I want to have an apple store account for 2 reasons only. 1. To download the art covers for my music 2. So iTunes stops asking me every 30 seconds 'do I want an iTunes account' At the end of registering I realised that apple are asking for my card de

  • 0FI_GL_4 data source input selection screen

    Dear experts, I have enabled the input selection option tickfor fields PRCTR and KOSTL in data source 0FI_GL_4 with RSA6. Both the fields are available in extract checker RSA3 too. But while does not have any effect while running the extractor. PRCTR

  • Import master and transaction data

    Hallo, I need the information, how I can import master and transaction data. I fellow the introductions from SAP.Help (see Link), but the Programm UPB_DATA_IMPORT is failed. (See point 3 in Link): http://help.sap.com/saphelp_nw04/helpdata/en/7a/6d313

  • HT204088 There is a charge on my cc bill for $3.99, but no such charge is listed in my purchase history.  What is this charge for?

    There is a charge on my credit card bill for $3.99, I cannot figure out what it is for.  I searched my purchase history, and nothing comes up that could be it.  Can somebody help me with this?  I am starting to think that maybe it is a subscrption to

  • Logon prompt is coming

    Hi, In portal I need to access quality server. For a certain iView when I clicked it in Q server, another logon prompt is coming showing that it referring to Production backend. I this case it should not asked for another login i.e. the iview must ge