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("'","'");
               result = result.replaceAll("\"",""");
          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.

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

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

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

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

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

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

  • Help: String.replaceAll(regex,string) !!!

    i want to replace a string(called str) such as
    "Don't hesitate to cantact us "
    into
    "Don\'t hesitate to cantact us "
    what statment i should take ??
    i am in a Jsp page, with
    <%= str.replaceAll("'", "\'") %> or
    <%= str.replaceAll("'", "\\'") %> or
    <%= str.replaceAll("'", "\\\'") %>
    i got always wrong or unchanged string ...
    Help !!!!!!!!!!!!!!!!!!!!!!!!!

    well if your tomcat uses jdk1.4 or above you can import java.util.Regx.* and use replaceAll() method on string in your jsp page, otherwise write your own code to substring the two string & add "\" at the end of the first string then join the two substrings.

  • 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

  • Need help in the String Format method

    really need help in string.Format method. I would like to show the s in two digit numbers.
    for example:
    if s is below 10 then display *0s*
    the expecting result is 01,02,03.. 09,10,11....
    I tried this method, somehow i got the errors msg. pls advise. thx.
    public void setDisplay(String s) {
    String tmpSS=String.format("%02d",s);
    this.ss.setText(tmpSS);
    Edited by: bluesailormoon on May 19, 2008 10:30 AM

    Apparently, you expect the string to consist of one or two digits. If that's true, you could do this:String tmpSS = (s.length() == 1) ? ("0" + s) : s; or this: String tmpSS = String.format("%02d", Integer.parseInt(s));

  • Question about the java doc of String.intern() method

    hi all, my native language is not english, and i have a problem when reading the java doc of String.intern() method. the following text is extract from the documentation:
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
    i just don't know the "a reference to this String object is returned" part, does the "the reference to this String" means the string that the java keyword "this" represents or the string newly add to the string pool?
    eg,
    String s=new String("abc");  //create a string
    s.intern();  //add s to the string pool, and return what? s itself or the string just added to string pool?greate thanks!

    Except for primitives (byte, char, short, int, long, float, double, boolean), every value that you store in a variable, pass as a method parameter, return from a method, etc., is always a reference, never an object.
    String s  = "abc"; // s hold a reference to a String object containing chars "abc"
    foo(s); // we copy the reference in variable s and pass it to the foo() method.
    String foo(String s) {
      return s + "zzz"; // create a new String and return a reference that points to it.
    s.intern(); //add s to the string pool, and return what? s itself or the string just added to string pool?intern returns a reference to the String object that's held in the pool. It's not clear whether the String object is copied, or if it's just a reference to the original String object. It's also not relevant.

  • Strange behavior of std::string find method in SS12

    Hi
    I faced with strange behavior of std::string.find method while compiling with Sunstudio12.
    Compiler: CC: Sun C++ 5.9 SunOS_sparc Patch 124863-14 2009/06/23
    Platform: SunOS xxxxx 5.10 Generic_141414-07 sun4u sparc SUNW,Sun-Fire-V250
    Sometimes find method does not work, especially when content of string is larger than several Kb and it is needed to find pattern from some non-zero position in the string
    For example, I have some demonstration program which tries to parse PDF file.
    It loads PDF file completely to a string and then iterately searches all ocurrences of "obj" and "endobj".
    If I compile it with GCC from Solaris - it works
    If I compile it with Sunstudio12 and standard STL - does not work
    If I compile it with Sunstudio12 and stlport - it works.
    On win32 it always works fine (by VStudio or CodeBlocks)
    Is there any limitation of standard string find method in Sunstudio12 STL ?
    See below the code of tool.
    Compilation: CC -o teststr teststr.cpp
    You can use any PDF files larger than 2kb as input to reproduce the problem.
    In this case std::string failes to find "endobj" from some position in the string,
    while this pattern is located there for sure.
    Example of output:
    CC -o teststr teststr.cpp
    teststr in.pdf Processing in.pdf
    Found object:1
    Broken PDF, endobj is not found from position1155
    #include <string>
    #include <iostream>
    #include <fstream>
    using namespace std;
    bool parsePDF (string &content, size_t &position)
        position = content.find("obj",position);
        if( position == string::npos ) {
            cout<<"End of file"<<endl;
            return false;
        position += strlen("obj");
        size_t cur_pos = position;
        position = content.find("endobj",cur_pos);
        if( position == string::npos ){
            cerr<<"Broken PDF, endobj is not found from position"<<cur_pos<<endl;;
            return false;
        position += strlen("endobj");
        return true;
    int main(int argc, char ** argv)
        if( argc < 2 ){
            cout<<"Usage:"<<argv[0]<<" [pdf files]\n";
            return -3;
        else {
            for(int i = 1;i<argc;i++) {
                ifstream pdfFile;
                pdfFile.open(argv,ios::binary);
    if( pdfFile.fail()){
    cerr<<"Error opening file:"<<argv[i]<<endl;
    continue;
    pdfFile.seekg(0,ios::end);
    int length = pdfFile.tellg();
    pdfFile.seekg(0,ios::beg);
    char *buffer = new char [length];
    if( !buffer ){
    cerr<<"Cannot allocate\n";
    continue;
    pdfFile.read(buffer,length);
    pdfFile.close();
    string content;
    content.insert(0,buffer,length);
    delete buffer;
    // the lets parse the file and find all endobj in the buffer
    cout<<"Processing "<<argv[i]<<endl;
    size_t start = 0;
    int count = 0;
    while( parsePDF(content,start) ){
    cout<<"Found object:"<<++count<<"\n";
    return 0;

    Well, there is definitely some sort of problem here, maybe in string::find, but possibly elsewhere in the library.
    Please file a bug report at [http://bugs.sun.com] and we'll have a look at it.

  • 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

Maybe you are looking for