PatternSyntaxException w/ replaceAll

String msg="what is up?";
String[] s = msg.split(" ");
String[] r = {"?","!",",",".","+"};
for(int i=0;i<s.length;i++){
     for(int j=0;j<r.length;j++){
          if(s.contains(r[j])){
s[i]=s[i].replaceAll(r[j], "");
Throws: Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0 @ the replaceAll
Some googling showed that adding "\\" in front of the ? should fix it. But this doesn't seem to work. (IE r = {"\\?","!",",",".","+"}; )
It doesn't see that "\\?" is contained.
So I removed the check for containing...
String msg="what is up?";
String[] s = msg.split(" ");
String[] r = {"\\?","!",",",".","\\+"};
for(int i=0;i<s.length;i++){
     for(int j=0;j<r.length;j++){
          s=s[i].replaceAll(r[j], "");
System.out.println(s[i]);
It prints out nothing.
So some how, s[i] is empty after it replaces everything. I don't understand what's happening.
How can i remove these characters from my String?

Oops: Watch your dot ;-) replaceAll(".", "") removes all chacters from the string (except EOL's by default).
class Replacerator
  public static void main(String[] args) {
    try {
      for ( String word : "What's up?".split(" ") ) {
        word = word.replaceAll("(?<=[A-Za-z])'s", " is");
        for ( String replacement : new String[]{"\\?", "!", ",", "\\.", "\\+"} ) {
          word = word.replaceAll(replacement, "");
        System.out.println(word);
    } catch (Exception e) {
      e.printStackTrace();
}Cheers. Keith.

Similar Messages

  • 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

  • PatternSyntaxException: Dangling meta character '*' near index 0

    Hi,
    I am using DocumentFilter to control the input in a JtextField In accordance with model of a mask.
    The mask can contain the following characters:
        //  # :  for  =---> NUMBER only
        //  ? :  for  =---> LETTER only
        //  A :  for  =---> LETTER end for NUMBER
        //  * :  for  =---> ANYTHING    I made a class that extends DocumentFilter and it look like this:
    public class MydocumentFilter extends DocumentFilter {
    public void insertString(...){
    // do anything
        } // insertString()
    public void remove(...)
    // do anything
        } // remove()
    @Override
        public void replace(
                DocumentFilter.FilterBypass fb,
                int offset, // posizione del cursore
                int length, // Length of text to delete (solo per sostituzioni...)
                String text,// testo da inserire
                AttributeSet attrs) throws BadLocationException {
    // here are some controls that change the value of the text variable, and at last call the super class..:
            super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);
        } // replace()
    } // class  MydocumentFilterI have a problem when the user write wildcards (='*' OR '?').
    Then I get the message:
    Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0.I know that '*' and “?” are is a metachars and for that I added this code before calling super.replace(...);
            if (text.compareTo("*") == 0){
                replace = "\\*";
            }but I don't get the expected result. I get -\*- instead then -*-
    here the code of the program that I use to make tests:
    * http://www.java2s.com/Tutorial/Java/0260__Swing-Event/CustomDocumentFilter.htm
    * @author Owner
    //public class IntegerRangeDocumentFilter extends DocumentFilter {
    public class NavBean_documentFilter extends DocumentFilter {
        enum CharAcceptability_ENUM {
            valid, invalid, overrite
        String mask;
        public NavBean_documentFilter(String mask_) { // constructor
            mask = mask_;
        } // constructor
        @Override
        public void insertString(
                DocumentFilter.FilterBypass fb,
                int offset,
                String string,
                AttributeSet attr) throws BadLocationException {
            System.out.println("insert string" + string);
            System.out.println(offset);
            super.insertString(fb, offset, string, attr);
        } // insertString()
        @Override
        public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
                throws BadLocationException {
            System.out.println("remove");
            super.remove(fb, offset, length);
        } // remove()
        public void replace(
                DocumentFilter.FilterBypass fb,
                int offset, // posizione del cursore
                int length, // Length of text to delete (solo per sostituzioni...)
                String text,// testo da inserire
                AttributeSet attrs) throws BadLocationException {
            boolean valid = true;
            if (offset > mask.length()) {
                return;
            if (text.length() != 1) {
                return;
            CharAcceptability_ENUM charAcceptability_ENUM = checkTheInput(text, offset);
            String replace = null;
            switch (charAcceptability_ENUM) {
                case invalid:
                    replace = "";
                    break;
                case valid:
                    replace = text;
                    break;
                case overrite:
                    char cc = mask.charAt(offset);
                    replace = String.valueOf(cc);
                    break;
            // It is because * is used as a metacharacter to signify one or more
            // occurences of previous character.
            // So if i write M* then it will look for files MMMMMM..... !
            // Here you are using * as the only character so the compiler
            // is looking for the character to find multiple occurences of,
            // so it throws the exception.:)
            if (text.compareTo("*") == 0){
                replace = "\\*";
            text = replace;
            super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);
    //        super.replace(fb, offset, length, text, attrs);
        } // replace()
        private CharAcceptability_ENUM checkTheInput(String text, int cursorPosition) {
            if (cursorPosition >= mask.length()) {
                return CharAcceptability_ENUM.invalid;
            char mappedCharInTheMask = mask.charAt(cursorPosition); // qui erro
            char charToSet = text.charAt(0);
            System.out.println("carattere da mettere = " + charToSet + " ; carattere della maschera = " + mappedCharInTheMask);
            boolean placeHolderFree = mask.contains(String.valueOf(mappedCharInTheMask));
            if (!placeHolderFree) {
                return CharAcceptability_ENUM.invalid;
            CharAcceptability_ENUM charAcceptability_ENUM =
                    CharAcceptability_ENUM.invalid;
            char holdPlace = mask.charAt(cursorPosition);
            switch (holdPlace) {
                case '*': // 
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case '#': // only numbers
                    if ( Character.isDigit(charToSet)) {
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case '?': //only letters
                    if (Character.isLetter(charToSet)){
                        charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                case 'A': // letters and numbers
                    if (Character.isLetterOrDigit(charToSet)){
                    charAcceptability_ENUM = CharAcceptability_ENUM.valid;
                    break;
                    default:
                        charAcceptability_ENUM = CharAcceptability_ENUM.overrite;
            System.out.println("valore di charAcceptability_ENUM = " + charAcceptability_ENUM.toString());
            return charAcceptability_ENUM;
        } // checkTheInput()
    } // class UsingDocumentFilter
    class RangeSample {
        public static void main(String args[]) {
            JFrame frame = new JFrame("Range Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // questo (in generale) e' quanto si deve fare per usare un filtro...
            JTextField textFieldOne = new JTextField();
            JLabel jLabMask = new JLabel();
            JPanel panel = new JPanel();
            String explanation1 = "      ---  use of wildCard: ---";
            String explanation2 = " #  :  is for  =---> only NUMBER ";
            String explanation3 = " ?  :  is for  =---> only LETTER ";
            String explanation4 = " A  :  is for  =---> LETTER end NUMBER";
            String explanation5 = " *  :  is for  =---> ANYTHING      ";
            JLabel jLabExplanat1 = new JLabel(explanation1);
            JLabel jLabExplanat2 = new JLabel(explanation2);
            JLabel jLabExplanat3 = new JLabel(explanation3);
            JLabel jLabExplanat4 = new JLabel(explanation4);
            JLabel jLabExplanat5 = new JLabel(explanation5);
            panel.setLayout(new GridLayout(5, 1));
            panel.add(jLabExplanat1);
            panel.add(jLabExplanat2);
            panel.add(jLabExplanat3);
            panel.add(jLabExplanat4);
            panel.add(jLabExplanat5);
            jLabExplanat1.setForeground(Color.green);
            jLabExplanat2.setForeground(Color.red);
            jLabExplanat3.setForeground(Color.red);
            jLabExplanat4.setForeground(Color.red);
            jLabExplanat5.setForeground(Color.red);
            jLabMask.setForeground(Color.blue);
            //AAA-##:***
            String mask = "##-A#A:#????  ***";
    //        String mask = "***";
            Document textDocOne = textFieldOne.getDocument();
            NavBean_documentFilter filterOne = new NavBean_documentFilter(mask);
            ((AbstractDocument) textDocOne).setDocumentFilter(filterOne);
            String jLabelTxt = "mask to use :  " + filterOne.mask + "   ";
            jLabMask.setText(jLabelTxt);
            frame.setLayout(new GridLayout(3, 1));
            frame.add(panel);
            frame.add(jLabMask);
            frame.add(textFieldOne);
            frame.pack();
            frame.setLocation(300, 150);
            frame.setVisible(true);
        } // main()
    } // class RangeSampleany advice shall be appreciated
    thank you
    regards
    Angelo Moreschini

    All that many lines for a regex question (where the error message already pointed to), which has nothing to do with Swing. An SSCCE looks different.
    if (text.compareTo("*") == 0){
    replace = "\\*";
    text = replace;
    super.replace(fb, offset, length, text.replaceAll(text, replace), attrs);You must keep the text, the regex and the replacement string apart:
    String text= "A", regEx= "A", rep= "B";
    //String text= "*", regEx="\\*", rep= "*";
    text= text.replaceAll(regEx, rep);
    System.out.println(text);And why don't you use a JFormattedTextField with a MaskFormatter which does all the job for you.

  • ReplaceAll regexp and JavaScript

    I want to write a function that will escape special characters in a String so that they render correctly in JavaScript.
    For example, if a string contains a tab, I want the tab to be replaced by \t and so on for all the escape characters : \', \", \\, \b, \f, \n, \t and \r.
    Here is my function so far :
    public static String JSStringFormat(String value) {
        String result = "";
        if (value != null) {
            result = value;
            result = result.replaceAll("\'", "\\\\'");
            result = result.replaceAll("\b", "\\\\b");
            result = result.replaceAll("\f", "\\\\f");
            result = result.replaceAll("\n", "\\\\n");
            result = result.replaceAll("\t", "\\\\t");
            result = result.replaceAll("\r", "\\\\r");
        return result;
    }So far, this works... But I can't find the solution for \\ and \"... I've tried many things but nothing works...
    Anyone can help ?

    replaceAll("\"", "\\\""); // I thinkIt throws compilation error on this line itself. If
    you are using an IDE, it wont allow you to go further
    with that line.
    replaceAll("\\\\", "\\\\\\\\"); // I think.
    I had a slight error in the quote one the replacement string needed two more quotes. This works:         String str = "\\a \"xyz\" \\ b";
            System.out.println(str);
            //System.out.println(str.replaceAll("\\" , "\\\\\\"));
            System.out.println(str.replaceAll("\"", "\\\\\""));
            System.out.println(str.replaceAll("\\\\", "\\\\\\\\"));Your line (commented above) gives Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
    ^
    regEx is particular about special characters like $
    and \.Yes, I know.
    So when you are using replaceAll, you have to
    be careful with regex, and replace them. For example,
    if you have a $ to be replaced, you have to replace
    it the following way.
    str.replaceAll("\\$", "\\\\\\$");Yes.
    >
    so, instead of directly using the $, you have to use
    "\\" that tells the regEx, yes this is a special
    character and treat it normally, like any other
    character.Yes.
    Along those same lines, like I said, you need \\ to get a single \ in a Java String. Then, if you want a literal \ in the regex, you need to provide the regex compiler with \\, which means your Java String literal must be \\\\.

  • How to use replaceAll()

    I have a string
    s = "hai hai hai".
    i want to replace "ai" with "ello" so that my string reads "hello hello hello". i used the syntax
    s = s.replaceAll("ai",ello").
    the code compiles fine, but i am getting theexception
    "java.util.regex.PatternSyntaxException: Unmatched closing ')' "
    can anyone tell me the correct syntax?

    sorry I didn't get you...You didn't post your actual code, I guess.
    It is better to post the relevant part of your code instead of posting non-compilable statments (including typos.)
    The following code works perfectly:String s = "hai hai hai";
    s = s.replaceAll("ai", "ello");
    System.out.println(s);Moreover, the exception suggests that you have a parenthesis in your String, which is not the case in what you've posted.
    My guess is therefore: the error is not related to this replaceAll thing.
    Anyway, remember that the first parameter of the replaceAll method is a regular expression. Consequently, some characters (e.g. parenthesis) have special meaning.

  • PatternSyntaxException: Unclosed character class near index

    Hi,
    I want to replace in a string a expression like "^1:2" by "^(1/2)":
    For example, "V/Hz^1:2" would be converted to "V/Hz^(1/2)".
    I tried the following code:
    String oldExponent = "[^](\\d+):(\\d+)"; // e.g. ^1:2
    String newExponent = "^($1/$2)";         // e.g. ^(1/2)
    myString = myString.replaceAll(oldExponent, newExponent);but the following exception is thrown in the third line:
    java.util.regex.PatternSyntaxException: Unclosed character class near index 13
    [^](\d+):(\d+)
                 ^Any idea?
    Thanks in advance.

    Thank you, jverd, you are pretty right.
    Now I tried with
    "\\^(\\d+):(\\d+)"and it works.
    I tried to avoid ^ being interpreted as the beginning of the line, and didn't realize the interpretation inside the brackets.
    Escaping this character works well.

  • 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

  • Help with PatternSyntaxException

    II hope someone can help me. I have been struggling with this for hours. I cannot seem to get my try block to throw the error/or catch it. Plus, it looks like my efforts to use overloaded constructors may have also backfired and now it is overwriting the value to null when wrong input data. Please look at the code if you would and comment on my design decisions if you would.
    This is my header file:
    import java.util.*;
    import java.util.regex.*;
    class Email {
    //class variable to set state
    public static final String notKnown = "Unknown";
    public static final Pattern ePattern= Pattern.compile("[\\w\\.\\-]+\\@[\\w\\.\\-]+\\.[\\w\\.\\-]+");
    public static Matcher ematch;
    //declare class's member variables
    private String senderName;
    private String recipientName;
    private String subject;
    private Date dateOfEmail;
    private String content;
    private Date dateReceived;
    private String senderEmail;
    private String receiverEMail;
    private String retPath;
    private String MessageID;
    private String org=notKnown;
    private String MIMEv=notKnown;
    private String XMail=notKnown;
    private String ContType=notKnown;
    //overloaded constructors to initialise variables and ensure consistent state
    public Email()
    this(notKnown,notKnown,notKnown,notKnown,notKnown,notKnown);
    public Email(String send,String sendEmail, String r, String recEmail)
    this(send,sendEmail,r,recEmail,notKnown,notKnown);
    public Email(String send,String sendEmail, String r, String recEmail, String sub)
    { this(send,sendEmail,r,recEmail,sub,notKnown);
    public Email(String send, String sendEmail,String r,String recEmail,String sub, String c)
    setSenderName(send);
    setSenderEmail(sendEmail);
    setRecipientName(r);
    setRecEmail(recEmail);
    setSubject(sub);
    setContent(c);
    dateOfEmail = new Date();
    public void setSenderName(String newSender)
    senderName = newSender;
    public String getSender()
    return senderName;
    public void setSenderEmail(String SendAdd)
    validateEmail(SendAdd);
    public String getSenderEmail()
    return senderEmail;
    public void setRecipientName(String newRecipient)
    recipientName=newRecipient;
    public String getRecipientName()
    return recipientName;
    public void setRecEmail(String recEAdd)
    receiverEMail = recEAdd;
    public String getRecEmail()
    return receiverEMail;
    public void setSubject(String newSubject)
    subject=newSubject;
    public String getSubject()
    return subject;
    public void setContent(String newContent)
    content = newContent;
    public String getContent()
    return content;
    public Date getDate()
    return dateOfEmail;
    public void setMessageID(String mID)
    MessageID = mID;
    public String getMessageID()
    return MessageID;
    public void setOrganization(String orgName)
    if (orgName==" ")
    org=org;
    else
    org=orgName;
    public String getOrganization()
    return org;
    public void setMIMEv(String mime)
    if (mime==" ")
    MIMEv=MIMEv;
    else
    MIMEv=mime;
    public String getMIMEv()
    return MIMEv;
    public void setXmail(String xm)
    if (xm==" ")
    XMail=XMail;
    else
    XMail=xm;
    public String getXmail()
    return XMail;
    public void setContentType(String ct)
    if (ct==" ")
    ContType=ContType;
    else
    ContType= ct;
    public String getContentType()
    return ContType;
    public void validateEmail(String validEmail)
    try { ematch=ePattern.matcher(validEmail);
    if (ematch.find())
    senderEmail=validEmail;
    catch (PatternSyntaxException exception)
    { System.out.println("In catch block");
    System.out.println(exception.getMessage());
    This is my Test File:
    import java.util.*;
    public class EmailTest{
    public static void main(String[]args)
    Email email;
    String whoFrom;
    String whoTo;
    String subject;
    String content;
    email = new Email();
    System.out.println("Email: " +
    "\n From: " + email.getSender() + " " + email.getSenderEmail() +
    "\n To: " + email.getRecipientName()+ " " + email.getRecEmail() +
    "\n Subject: " + email.getSubject() +
    "\n Date: " + email.getDate().toString() + "\n Company: " + email.getOrganization()+ "\n MIME v.: " + email.getMIMEv() +
    "\n X-mailer: " + email.getXmail() +
    "\nContent Type: " + email.getContentType() +
    "\n Message: " + email.getContent() + "\n");
    email.setSenderName("\"Jimmy Testsender\"");
    email.setSenderEmail("<fnTrevorWazoo.com>");
    email.setRecipientName("\"Sheena Receiver\"");//@WaZoo
    email.setRecEmail("<[email protected]>");
    email.setSubject("How are you today?");
    email.setOrganization("WaZoo.com");
    email.setMIMEv("1.0");
    email.setXmail(" ");
    email.setContentType(" ");
    email.setContent(" I just wrote an email class!");
    System.out.println("Email: " +
    "\n From: " + email.getSender() + " " + email.getSenderEmail() +
    "\n To: " + email.getRecipientName()+ " " + email.getRecEmail() +
    "\n Subject: " + email.getSubject() +
    "\n Date: " + email.getDate().toString() + "\n Company: " + email.getOrganization()+ "\n MIME v.: " + email.getMIMEv() +
    "\n X-mailer: " + email.getXmail() +
    "\nContent Type: " + email.getContentType() +
    "\n Message: " + email.getContent() + "\n");
    and this is what I get when wrong input (validation seems to work):
    the email keeps saying null (so its overwriting or something)
    Pleasssssssssssssse help I have an assignment due in less than 2 days and this is slowing me down
    Thanks guys, I could really use some help

    You'll only get a PatternSyntaxException if your pattern is broken.
    Read up on the documentation for that PatternSyntaxException.
    Maybe you'll want to change your validateEmail() method to return boolean?
    If you want to see an exception being caught, just throw your own     public boolean validateEmail(String validEmail) {
              try {
                   ematch=ePattern.matcher(validEmail);
                   if (ematch.find()) {
                        senderEmail=validEmail;
                        return true;
                   else
                        throw new IllegalArgumentException("Does not match a valid Email address");
              catch (IllegalArgumentException exception) {
                   System.out.println("In catch block");
                   System.out.println(exception.getMessage());
              return false;
         }

  • 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

  • Different results using Matcher.replaceAll on a literal depending on the Pattern compiled

    I would have expected that the results for all the following scenarios would have been the same:
    public class PatternMatcher {
        public static void main(String[] args) {
            Pattern p;
            Matcher m;
            // duplicates
            p = Pattern.compile("(.*)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("(.+)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // wtf
            p = Pattern.compile("(.*?)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // duplicates
            p = Pattern.compile("(.*+)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("^(.*)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // duplicates
            p = Pattern.compile("(.*)$");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("^(.*)$");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
            // single
            p = Pattern.compile("(.(.*).)");
            m = p.matcher("abc");
            if (m.matches()) System.out.println(p + " : " + m.replaceAll("xyz"));
    But the results vary depending on the pattern compiled:
    (.*) : xyzxyz
    (.+) : xyz
    (.*?) : xyzaxyzbxyzcxyz
    (.*+) : xyzxyz
    ^(.*) : xyz
    (.*)$ : xyzxyz
    ^(.*)$ : xyz
    (.(.*).) : xyz
    Since all of the patterns have an all-encompassing capture group, but the replacement string does not have any group references, I was expecting that in every case the replacement string would simply be returned unchanged (so just "xyz").
    Have I uncovered a bug in the core library?  or am I misunderstanding how this should be working?

    jwenting wrote:
    And such is the case here.
    "You're doing it wrong, but I'm not going to tell you what it is you're doing wrong nah nah nah"
    That's the good thing about long lasting platforms such as Java - APIs become mature because they've been tested and re-tested by thousands of people for more than a decade. And thus when you go to use them and have to think "wtf", you can be almost certain you simply don't understand and meanies in forums can say so without having any ammunition to back up that accusation.

  • Using a local variable in regex portion of replaceAll(regex, replacement)

    While this works..
    output = output.replaceAll("(HED>|AUT>)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    I'd like the list of alternation values to be contained in a variable, for example:
    String nodeLIst = "HED>|AUT>";
    output = output.replaceAll("(nodeList)(.*)(</\\1)", "$1<![CDATA[$2]]>$3");
    The extension of this would be so I can store this stuff in a db as a list and avoid compilation on change, but please don't let this muddy the waters... :)
    Any pointers are much appreciated. Links to specific reading material, etc. I've scoured Friedl's Mastering Regular Expressions to no avail. This approach is supported by some other regex engines I've used (perl, php, ORO?) but I'm new to Java.
    TIA,
    Mark

    I've scoured Friedl's Mastering Regular Expressions to no avail.Did you look on page 209? In the book, that code sample is labelled "Building Up a Regex Through Variables in Java". That should have been a clue. ^_^
    But seriously, you're probably thinking of the interpolated strings you find in scripting languages like Perl, PHP, Ruby, etc.. But that's a feature of the language itself, not the regex engine, and Java doesn't work that way. (The $1, $2, etc., in the replacement string are processed by the Matcher class, in a very limited imitation of Perl's variable interpolation).
    However, you can fake it pretty well with String's format() method:   String regex = String.format("(%s)(.*)(</\\1)", theAlternation);
      output = output.replaceAll(regex, "$1<![CDATA[$2]]>$3"); That way, you can easily escape the dynamic part, in case it might contain regex metacharacters:   String regex = String.format("(%s)(.*)(</\\1)", Pattern.quote(theAlternation));

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

  • Can replaceAll do what I want?

    Hi
    I have a string "This is My string my way"
    This text will be in a button's text property.
    What I would like to do is add a html tag like the font tag to certain parts of the string to make it another color.
    The user will for instance provide the input "my" ,all input will be lowercase.
    Then it should add the following tag to the string : "This is <font>My</font> string <font>my</font> way"
    This should be done for all matching strings upper and lower case.
    I had a look at replaceAll, but it will replace only the exact string so if the input is lowercase it won't be replaced. I also need to retain the case of the "replaced" string so that "My" does not change to "<font>my</font>"
    Can replaceAll be used to do what I want?
    Some examples would be appreciated.
    Thanks

    The first argument to replaceAll() is a regular expression, which means you can do a lot more than just match case-insensitively, but here's how you would do that:  String str2 = str1.replaceAll("(?i)my", "<font>$0</font>");You might find these links useful:
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html
    http://www.regular-expressions.info/

  • Problem with the replaceAll method - please help

    When the source String contains some special characters like ' ? ' , ' ) ' , or ' ( ' etc, the replaceAll function doesn't has any effect on the source String.
    for example
    String k="images/mainpage7(sm)_01.jpg";
    String h=k.replaceAll("images/mainpage7(sm)_01.jpg","JoinNowBox_01.jpg");
    System.out.println(k);
    System.out.println(h);
    output:
    images/mainpage7(sm)_01.jpg
    images/mainpage7(sm)_01.jpg
    Can anybody tell me what to do?
    Thanks in advance
    Hristos Floros - Greece

    But what if I don�t know the values of all Strings?
    String a="images/mainpage7(sm)_01.jpg";
    String b="images/mainpage7(sm)_01.jpg";
    String c="images/mainpage7(sm)_01.jpg";
    String d=a.replaceAll(b,c);
    System.out.println(a);
    System.out.println(d);

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

Maybe you are looking for

  • Max locate size

    hello, does anyone know the max locate size that a SNASw router will set for the locate process ? For VTAM is 16K, for the Cisco Snasw ? I can't find this on the doc and I think my "location" problem depends on this. Many thanks in advance to the peo

  • Motion export blurry in DVDSP

    i exported a sequence from motion 720 by 480 to animation and just basic ntsc dv i imported the file to DVDSP to use as a motion menu and some of the text is fuzzy and just not crisp...its really frustrating the video itself plays beautifully as a st

  • Standard report to extract contract open quantity

    Dear Expert, I'm facing this problem: I'm using ME80RN to extract information about contracts but I can't find in the field catalogue the "open Target Quantity" field. I know I can find it in ME3L/M but the format it extracts data is not compliance w

  • How do I simply move .jpg photos from my win7 PC to my iphone 4?

    I am having trouble moving photos from my win7  PC to my new iphone 4.  I emailed a few but that's too inefficient.  I tried drapping and dropping with itunes but it says the phone's not connected, it is and I have moved other apps and items but phot

  • Xterm sometimes fail to wrap when typing

    When typing a long command (beyond the window edge) xterm will sometimes fail to wrap to a new line and instead begin writing over the current line. It's like it does a \r (carriage return) when it should have done a \n (new line). The result is sort