String replaceAll() Help

    //kill characters method used to remove unwanted characters
    //from strings, takes in unedited string, returns formatted string
    private String killChars(String fixThis )
        return fixThis.replaceAll("\\W", "");
    }//endHey guys and gals.
I have this method in one of my applications and I'm not exactly getting the results I want. Is there a way to manipulate the arguments in the replaceAll function so that it will replace all non-alphanumeric except spaces? I actually want to keep whitespace.
Thanks,
Kyle

Thanks, that seems to be much better. I was looking through the patterns on Oracles help site and they are very confusing. This works though, thanks!

Similar Messages

  • Problem in String.replaceAll please help

    String ash = "XXX";
    String ch = ash.replaceAll("X","$");
    while executing the above code i am getting an exception
    java.lang.StringIndexOutOfBoundsException: String index out of range: 1
         at java.lang.String.charAt(Unknown Source)
         at java.util.regex.Matcher.appendReplacement(Unknown Source)
         at java.util.regex.Matcher.replaceAll(Unknown Source)
         at java.lang.String.replaceAll(Unknown Source)
    please help me
    baiju

    Cross-post
    http://forum.java.sun.com/thread.jspa?threadID=607145

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

  • Sort a string :: Please help.

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

    Hello Everyone,
    I am having this very simple problem of sorting a String. please help.
         static String sortString(String str){
              List list = Arrays.asList(str);                    
              Collections.sort(list);
              for(int i=0, n=list.size();i<n;i++){
                   System.out.println(","+ list.get(i));
                   return str;
    The function is supposed to take a String and sort it & print it out. This should be simple. Where am I making mistakes? Please help!!

  • Pass username and password ADFS without using query string, Please help.

    pass username and password ADFS without using query string, Please help.
    I used query string , but it is unsecured to pass credentials over url, with simple tool like httpwatch , anyone can easily get the password and decrypt it.

    Hi,
    According to your post, my understanding is that you had an issue about the ADFS.
    As this issue is related to ADFS, I recommend you post your issue to the forum for ADFS.
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/home?forum=Geneva
    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us.
    Thank you for your understanding and support.
    Thanks,
    Jason
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Jason Guo
    TechNet Community Support

  • 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

  • Bug in String.replaceAll()

    Hi folks,
    Have anybody try to do the following with String.replaceAll()?
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\");
    It will throw IndexOutOfBoundException.
    Billy Ng

    I'm not sure that's a bug, it's just the behavior of the underlying regex processor.
    Regardless, to get the effect you want, try:
    String path = "/ssss/ssss/sssss/";
    path.replaceAll("/", "\\\\");

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

Maybe you are looking for

  • Firefox (12.0, Ubuntu) freezes on Bing maps

    Hello, When I try and use Bing maps (maps.bing.co.uk, I live in UK), firefox gets very slow and freezes after about 3 zoom or move operations. I've tried disabling hardware acceleration - with accel on, the whole X server freezes, without it just fir

  • How to get full file name on MAC?

    Hi, In my plug-in, I have to get the full file name of the file opened in illustrator on MAC OS X. The following code works fine: SPPlatformFileSpecification theFileSpec; AIErr error = sAIDocument->GetDocumentFileSpecification(&theFileSpec); theFileS

  • Restricting access of a query in BI Authorization

    Hi, We have two group of users in BI. We have given access of a query to one user group. We want that the other group should not be able to access this query. Is there any way using which we can exclude this query in the role provided to second user

  • Can't have my number authenticated for 2 clients a...

    I have a Win install and a Mac install on different computers (same country) Why when I authenticate one client and my texts are displayed with my mobile number as a sender fine, I find the other client has lost this setting and I have to authenticat

  • Issue (aka bug):  File compatibility and alpha channels

    When I enable file compatibility mode on photoshop (so that previews and thumbnails show up), the thumbnail and preview will be wrong when there's an alpha channel in the channel palette. Specifically, the thumbnail will be masked by the top-most alp