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

Similar Messages

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

  • String.replaceAll doesn't work

    Hi,
    I hope this is the correct forum to post about this problem. It's not a compiler error, it rather seems to be an interpreter or a logical error.
    Please consider this test program I wrote to clarify the problem.
    public class Test {
        public static void main( String args[]) {
         String someString = "Hello $place!";
         System.out.println( someString.replaceAll( "place", "world"));
         System.out.println( someString.replaceAll( "$place", "world"));
    }The method String.replaceAll should replace all occurences of regex with replacement.
    Also see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)
    So, one should think my test program would have the following output:
    Hello $world!
    Hello world!Alas, it isn't so. The program outputs the following using SDK 1.2.4:
    Hello $world!
    Hello $place!The String.replaceAll method doesn't seem to replace occurences if they are preceeded of "$". Or am I just missing something?

    The String.replaceAll method doesn't seem to replace
    occurences if they are preceeded of "$". Or am I just
    missing something?You're right. The method replaceAll is expecting a [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html]regular expression. See there how to escape special control chars like $ which means 'end of line'.

  • PatternSyntaxException when calling String.replaceAll in multithreaded app

    Dear,
    Someone ever encountered or knows of problems when invoking String.replaceAll in a multithreaded application (JDK 1.4.2)?
    I have an application that invokes replaceAll on a String and that runs just fine when only a single thread is active, but once multiple threads execute the same code, each on its own String instance, the following stack is produced (more often than not).
    java.util.regex.PatternSyntaxException: Unknown character category {Digit} near index 9
    ^\p{Digit}
    ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.familyError(Unknown Source)
    at java.util.regex.Pattern.retrieveCategoryNode(Unknown Source)
    at java.util.regex.Pattern.family(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)
    at java.util.regex.Pattern.expr(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.util.regex.Pattern.<init>(Unknown Source)
    at java.util.regex.Pattern.compile(Unknown Source)
    at java.lang.String.replaceAll(Unknown Source)
    The 1.4.2 source code seems to use a static HashMap (java.util.regex.Pattern#retrieveCategoryNode) to store some read only data, but it looks like the initialization of that HashMap in an multi threaded environment is not 'locked'. Could that be the/an issue? Anybody any thoughts?
    Thanks,
    Peter

    I ran peter's program on a hyperthreaded Intel P4 box and XP Pro. XP reports that there are 2 processors.
    I used 1.4.2_06 and 1.5.0_01, with both -client and -server options.
    The program was run with numThreads 10 and loadPattern 0 and 1.
    The program was run 50 times for each of the configurations. Only one resulted in failures, as follows:
    Java version     cli/svr          Pgm Parms   # Failures      
    1.5.0_01     -client          10, 0          0
                        10, 1          0
              -server          10, 0          0
                        10, 1          0
    1.4.2_06     -client          10, 0          10
                        10, 1          0
              -server          10, 0          0
                        10, 1          0
    Of the 10 failures, 1 reported 3 errors, 2 reported 2 errors, and 7 reported 1 error.
    The triple-error report is below:
    "C:\Program Files\Java\jdk1.4.2_06\bin\java.exe" -client PatternProblem 10 0
    Thread-7:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Thread-5:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Thread-3:Unknown character category {Digit} near index 9
    ^\p{Digit}
             ^
    Note that this wording is not the same as peter encountered. The thread number varied,
    apparently randomly, from 0 to 8

  • String.replaceAll bottleneck

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

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

  • Matcher vs. String.replaceAll

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

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

  • String.replaceAll problem

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

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

  • Trouble with String.replaceAll( )

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

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

  • String.replaceAll(String,"\\")

    Hello, i tried this here but strangely it does not work.
    The machine gives an ArrayIndexOutOfBoundsException...
    Seems the method does not run with the "\" character. What did i do wrong?
    public class Zeichen {
         public static void main(String[] args) {
              Zeichen ch = new Zeichen();
         public Zeichen() {
              String str = "this";
              str=str.replaceAll("i","\\");
              System.out.println(str);
    }

    The method header for the String.replaceAll() that you are trying to use is as follows
    public String replaceAll(String regex,
                             String replacement)[\code]
    The string "i" that you are entering is not a regular expression, which are listed at http://java.sun.com/j2se/1.4/docs/api/java/util/regex/Pattern.html#sum

  • How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?

    Hi All,
    Hope to you a very happy new year,
    I have two differnt LAP 1300 and 1200 in my network and I need to add theme to the WLC,
    I successed to add one of theme by the option 60 in the DHCP pool at the Core SW,
    So my quetion is below:
    How to use multiple VCI strings for lap 1300 and 1200 (option 60) in one pool?
    Thanks in Advanced,
    Ahmed,

    To add to Scott's post.  Option 60 would be useful if you needed to put certain types of AP on specific controllers.  Otherwise, no real need to use it for the most part.
    Though, I do recall an issue a few years ago that some windows machines had issues getting DHCP if option 43 is being returned.
    Now, on an IOS switch, you can only configure one option 60 per DHCP scope
    HTH,
    Steve
    Please remember to rate useful posts, and mark questions as answered

  • How can you use a format string to make all information in a string line up and stack up?

    I am trying to post data on screen using "format into string" and make all data line up into one indicator string

    Not exactly sure what you are looking for. Could you elaborate, or post a screen shot of what you are trying to accomplish. I would hate to give you an answer based on my interpretation of your problem.

  • How to use Native SQL String

    Hi all,
    How do i use Native SQL String in the Reciver JDBC Adapter.
    Do i need to change the message format could u suggest me some blogs on the same.
    Also please can anyone let me knw if i can use this for stored procedure.

    hi aditya,
    there shud be no format as such. for sql xml format there are specific structure. but for native sql there shudnt be any specific structure.
    as pointed in sap documentaion:
    Instead of an XML document format, a text is expected that represents any valid SQL statement.
    When inserting a line into a table the corresponding document looks as follows:
    INSERT INTO tableName  (column-name1, column-name2, column-name3) VALUES(‘column-value1’, ‘column-value2’, ‘column-value3’)
    so jus make sure that u give a valid sql statement becoz if will be passed as it is to the database and try ur scenario.
    regards,
    latika.

  • Using content from Strings attributes in Prefix text

    Hello all you EDD experts out there,
    I did not find this specific info in the struct app dev guide, so I am hoping someone else has figured this out at some point in time. Maybe this is trivial to programmers, but I am not one of them and also I don't know what the prefix definition string will allow. So all help is greatly appreciated.
    In my structured framemaker EDD, I am using attributes to collect usage info. It would be nice to be able to use the Strings type attribute for this, instead of collating all the usage info into one single String type. But I need to use the content in a prefix string.
    Prefix: used in: \t<$attribute[validity]>
    If the validity attribute is of the Strings type and I enter multiple string values, only the first one shows up. How can I make all strings show in the prefix ?
    Thanks in advance for the golden tip :-)
    Jang

    Hello Russ and Van,
    I was kind of worried that I was crossing the limits of what FM EDDs can do. It is not a big deal - I can use the one string to store all values, as I have been doing so far. It just looks a little ugly when the string gets longer and the substrings do not wrap nicely. Of course going fully XML and XSLT etc would be another option but that is overkill for this particular client and they won't pay for that. Making the output a little nicer to look at is not a high priority, as this particular output is only shown in a catalogue of repository items to be used internally by my cient, i.e. it will never show in publications for users.
    Thanks for confirming my intuition that I should stop searching for the holy grail...
    Jang

Maybe you are looking for

  • Avoiding Quality Loss

    When I import MiniDV videos into Premiere Elements, the resulting AVI's are of great quality. When I edit in Premiere, even before exporting, the vid quality degrades horizontally. On vertical lines, there are jagged edges. Here's an example: Importe

  • I lost most of my pictures after i backed up my iPod

    hello fellow apple users! Today, while I was updating my iPod,which was connected to my computer;my Ipod started backing up just like that. I hadn't backed up my Ipod in a long time,which I now know wasn't a good idea.Since i hadn't already backed it

  • "Gleiche Farbe" in Photoshop CS

    Wenn ich mit der Funktion Bild > Anpassen > Gleiche Farbe die Farbstimmung eines Bildes dem eines anderen anpassen will, kommt häufig die Meldung "Konnte den Vorgang nicht ausführen, weil ein Programmfehler auftrag" - und bald danach geht es wieder,

  • Contact coverage rate report(very complex, combine analysis)

    Hi experts, we have a KPI to measure the contact coverage base on segmentation. the business scenario is as following: 1. We have 4 segments for tcontact, A, B, C, D. it is the custom filed in contact object; 2. my contact: if I am in the contact tea

  • Why is my startup disc full?

    I have a MacBook, and I use iMovie a ton. Like a LOT (I'm on YouTube) I keep getting notifications saying my start up disc is full, and I'll delete some stuff and it helps a little bit. But then it comes back! I've deleted as much as I can (there is