ReplaceAll with metacharacter

Hi all
I need to replace a String contains $ sign with another String contains $sign. Since $ sign have special meaning and need to add metacharacter between the message. I have some problem when the String used for replacement have $ sign. A exception generated
java.lang.IllegalArgumentException: Illegal group reference
Here are my coding
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public final class ReplaceTest {
    private static String REGEX = "\\Q$person.firstName $person.lastName<br/>\\E";
    private static String INPUT = "<p>#foreach($person in $personList)<br />$person.firstName $person.lastName<br/>#end</p>";
    private static String REPLACE = "\\$person.firstName1 \\$person.lastName1<br/>";
    private static String REPLACE1 = "\\Q$person.firstName1 $person.lastName1<br/>\\E";
    public static void main(String[] argv) {
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT);
        INPUT = m.replaceAll(REPLACE);
        System.out.println(INPUT);
}using REPLACE without problem but not REPLACE1. Since this String will read from file rather than input at coding level, I cannot add backslash in front of every $. Any solution for this? Thanks.
regards
wayne

Surfing 1.5 days and found the solution finally.
http://forum.java.sun.com/thread.jspa?threadID=561335&messageID=2760175

Similar Messages

  • ReplaceAll with file-path

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

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

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

  • String - replaceAll / with // 's

    hello fellow java developers!
    Im having some trouble, and it seems retarded.
    I have a String in the format "aaa/bbb/ccc/ddd" and I want to convert it to the format "aaa//bbb//ccc//ddd"
    I tried
    strPath = strPath.replace("\\", "\\\\"); - but its giving me an error!
    java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
    ^
    huh? why doesnt this work? the slashes are escaped...

    thes wrote:
    hello fellow java developers!
    Im having some trouble, and it seems retarded.
    I have a String in the format "aaa/bbb/ccc/ddd" and I want to convert it to the format "aaa//bbb//ccc//ddd"
    String s = "aaa/bbb/ccc/ddd";
    s = s.replace("/", "//");

  • How to remove the blank lines at the end of the JTextArea .

    Hi,
    I need to remove the blank lines in the JTextArea at the end. Suppose i am giving 'A' in the first line and press the enter key two times, after i am giving the 'B' in the third line and press enter key for two times. I need to remove, the last two lines of JTextAreae, . How i can remove these lines?

    String#trim() removes all whitespace from both ends of the String.
    The requirement was to remove line breaks from the end of the String only.
    String#replaceAll with a suitable regex would do the trick. Untested regex for this:text.replaceAll("[\\n\\r]+$", "")db

  • Blank lines at the end of SMS - iOS 4

    I've recently upgraded to the iPhone 4 from a 3G and messaging is so much faster, but for some reason occasionally when I send or receive an SMS there is a blank space at the bottom of the message, as if there's a carriage return there. This happens for both messages I send and receive, about every fifth message or so, and seems to be random.
    Anyone else noticed this? I've not had this issue before iOS 4 and although it isn't causing any problems with actually sending and receiving messages, it's quite annoying!

    String#trim() removes all whitespace from both ends of the String.
    The requirement was to remove line breaks from the end of the String only.
    String#replaceAll with a suitable regex would do the trick. Untested regex for this:text.replaceAll("[\\n\\r]+$", "")db

  • Char to string

    I can't seem to figure this out and maybe it's not possible but what im trying to do is make an array or the symbols like !@#$% and letters abcd... so I'm trying to just use the ASCII char codes... so i do (char)33 which is "!" and store it into an array but i want to make them strings so i can use replaceAll with another string

    Apple
    char is a primitive, not an Object, and primitives don't have methods. If this is how you want to do it, you should be looking at the class Character, or the constructors for String.
    This is just one of the many ways to get what you need:        String[] keys = new String[16];
            for(int i = 0; i < 16; i++ )
                Character tempChar = new Character((char) (i + 32));
                keys[i] = tempChar.toString();
            for (int i=0; i < keys.length; i++)
                System.out.println(keys);
    }Please take care in future to ask any question in a way that is easily understood.
    db

  • Regular Expression for non-words

    hello all!
    can you help me construct a regular expression that will match non-word strings say "������". I will be needing this to filter words from a Microsoft Word Document.
    Thanx!

    hello all!
    can you help me construct a regular expression that
    will match non-word strings say "������". I will
    be needing this to filter words from a Microsoft Word
    Document. I don't think this is a problem that should be solved with regex. You would have to convert your Word document to a String and use replaceAll() with "\\W" as the regex.
    Correct me if I am wrong but I thought that Word files were binary so your first problem will be to convert the file(s) to a String.

  • How to remove the maek up of a html document

    I have a HTML document. I want to remove all the mark up tags from the document and get all the content as a simple text.
    Please tell me how to do it.

    String.replaceAll with a cleverly created regex. Shouldn't be too difficult to remove everything that's a tag. In fact, I saw it done with a rather short regex the other day in another thread.

  • Problem with ReplaceALL-- Need Help

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

    Works fine on JRockit 1.5_015

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

  • .replaceAll("[a-zA-Z]", " ") with iso-8859-1

    Hi im using the swedish ��� letters. I want to replace parts in a text String with
    " .replaceAll("[^a-zA-Z_0-9]", " ")" but the problem is that it replaces the ��� letters to. I want to use the iso-8859-1 standard. But how?? Please help...

    sorry the latters i wanted to use is: &ouml; &auml;
    But the forum didnt support them.

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

  • 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

  • Problem with replaceAll method

    I have this string ; String text="hello my friend :-x";
    text=text.replaceAll(":-X","<img src=file:///c:\\test\\smileys\\1.gif />");
    The result is this : <img src=file:///c:textsmileys1.gif />
    Why is that ?
    How can i get the desired result ?
    Message was edited by:
    kynamar

    For best results, you should post complete, working test programs, so we can confirm your results before we start trying to solve your problem. None of the code you've posted so far works the way you say it does. Here's a sample program that should clarify things for you: public class Test
      public static void main(String[] args)
        String text="hello my friend :-x";
        System.out.println(text);
        // won't work: 'X' is in wrong case
        String text1 = text.replaceAll(":-X","<img src=file:///c:\\test\\smileys\\1.gif />");
        System.out.println(text1);
        // right case, but replaceAll eats the backslashes
        String text2 = text.replaceAll(":-x","<img src=file:///c:\\test\\smileys\\1.gif />");
        System.out.println(text2);
        // works, but what if a user really types ":-X"?
        String text3 = text.replace(":-x","<img src=file:///c:\\test\\smileys\\1.gif />");
        System.out.println(text3);
        // handles both cases, and satisfiies replaceAll's backslash addiction...
        String text4 = text.replaceAll(":-[xX]","<img src=file:///c:\\\\test\\\\smileys\\\\1.gif />");
        System.out.println(text4);
        // ...but you can almost always use forward-slashes instead
        // (plus, another way to deal with the case issue)
        String text5 = text.replaceAll("(?i):-X","<img src=file:///c:/test/smileys/1.gif />");
        System.out.println(text5);
    }

Maybe you are looking for

  • Network Setup - help!

    Hi all, I have finally gotten to the end of my tether with my attempts to set up my network here. Would someone please give me a step by step guide to what I should be doing? This is my configuration: 1 MacBook Pro 2 Laptops with Windows 1 Airport Ex

  • Calendar Prompt in OLAP Universe does on resolved.

    Hi, I am using BO XI 3.1 with latest fix pack. I have created a OLAP universe based on SSAS 2005 Multicube  for reporting using WebI. I have a date field in my database but when i but when i created a Universe based on that cube the date field became

  • Where is Adobe Acrobat?

    I cannot seem to find Adobe Acrobat in the Creative Cloud desktop app.  Can anyone tell me why that is?

  • I have iphone 4s, i want register to my apple id, but i cant (this iphone is registred to another id..)

    hi, i have iphone 4s, i want register to my apple id, but i cant (this iphone is registred to another id..) how i can register my iphone to my apple id?

  • Media Encoder Update for Captivate Subscription

    I see news that Adobe Media Encoder CC (7.2) is now available. http://www.adobe.com/support/downloads/detail.jsp?ftpID=5703 When I check for updates within Media Encoder CS6 (version 6.0.3.1) that came with my Captivate 7 subscription it says there a