ReplaceAll in a string.

Hi,
I need some help with regular expressions.
I need to replace all ocurences of string:
[a]some text that user inputs[a]
to:
<asdf>some text that user inputs</asdf>?
So the idea is that the user can input anything between [a] and [a] tags and I need to replace with some html code.
Example: user inputs [a]Here is my text[a]
I need to replace it with: <html><title>Here is my text</title><table><tr><td><font size=10>Here is my text</font></td></tr></table></html>
I want to use replaceAll method to do this. How would a call look like?
myString.replaceAll("[a]???[a]","<html><title>???</title><table><tr><td><font size=10>???</font></td></tr></table></html>");
What do I need to put in place of question marks (???)?
Thank you!

I don't know what you want to go in the ??? in the <font> element but
        String myString = "[a]some text that user inputs[/a] ";
        String result = myString.replaceAll("\\[a\\](.*?)\\[/a\\]","<html><title>$1</title><table><tr><td><font size=10>???</font></td></tr></table></html>");
        System.out.println(result);

Similar Messages

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

  • 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

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

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

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

  • How to replace regex match into a char value (in the middle of a string)

    Hi uncle_alice and other great regex gurus
    One of my friends has a peculiar problem and I cant give him a solution.
    Using String#replaceAll(), i.e. NOT a Matcher loop, how could we convert matched digit string such as "65" into a char of its numeric value. That is, "65" should be converted into letter 'A'.
    Here's the failing code:
    public class GetChar{
      public static void main(String[] args){
        String orig = "this is an LF<#10#> and this is an 'A'<#65#>";
        String regx = "(<#)(\\d+)#>";
        //expected result : "this is an LF\n and this is an 'A'A"
        String result = orig.replaceAll(regx, "\\u00$2");
        // String result = orig.replaceAll(regx, "\\\\u00$2"); //this also doesn't work
        System.out.println(result);

    I don't know that we have lost anything substantial.i think its just that the kind of task this is
    especially useful for is kind of a blind-spot in the
    range of things java is a good-fit for (?)
    for certain tasks (eg process output munging) an
    experienced perl programmer could knock up (in perl)
    using built-in language features a couple of lines
    which in java could takes pages to do. If the cost is
    readability/maintainability/expandability etc.. then
    this might be a problem, but for a number of
    day-to-day tasks it isn't
    i'm trying to learn perl at the moment for this exact
    reason :)Yes. And when a Java source-code processor(a.k.a. compiler) sees the code like:
    line = line.replaceAll(regexp,  new String(new char[] {(char)(Integer.parseInt("$1"))}));or,
    line = line.replaceAll(regexp,  doMyProcessOn("$1")); //doMyProcess returns a Stringa common sense should have told him that "$1" isn't a literal string "$1" in this regular expression context.
    By the way, I abhor Perl code becaus of its incomprehensibleness. They can't be read by an average common sense. Java code can be, sort of ...

  • Remove $%&* characters from a String

    Hi,
    I have the following program that is supposed to detect a subsequence from a String (that contains $ signs) and remove it. This is a bit tricky, since because of $ signs, the replaceAll method for String does not work. When I use replaceAll for removing the part of the String w/ no $ signs, replaceAll works perfectly, but my code needs to cover the $ signs as well.
    So far, except for replaceAll, I have tried the following, with the intent to first remove $ signs from only that specific sequence in the String (in this case from $d $e $f) and then remove the remaining, which is d e f.
    If anyone has any idea on this, I would greatly appreciate it!
    Looking forward to your help!
    public class StringDivider {
         public static void main(String [] args)
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
             String removeSymbols = "$d $e $f";
             int startIndex = symbols.indexOf(removeSymbols);
             int endIndex = startIndex + removeSymbols.length()-1;
             for(int i=startIndex;i<endIndex+1;i++)
                  if(symbols.charAt(i)=='$')
                       //not sure what to do here, I tried using replace(oldChar, newChar), but I couldn't achieve my point, which is to
                       //delete $ signs from the specific sequence only (as opposed to all the $ signs)
             System.out.println(symbols);
    }

    A little modification on the last version:
    This one's more accurate.
    public class StringDivider {
         public static void main(String [] args){
              String symbols = "$a $b $c $d $e $f $g $h $i $j $k l m n o p";
                  String removeSymbols = "$d $e $f $g";
                  if(symbols.indexOf(removeSymbols)!=-1)
                       if(removeSymbols.indexOf("$")!=-1)
                            removeSymbols = removeSymbols.replace('$', ' ').trim();
                            removeSymbols = removeSymbols.replaceAll("[ ]+", " ");
                            String [] symbolsWithoutSpecialChars = removeSymbols.split(" ");
                            for(int i=0;i<symbolsWithoutSpecialChars.length;i++)
                                 symbols = symbols.replaceAll("[\\$]*"+symbolsWithoutSpecialChars, "");
                             symbols = symbols.replaceAll("[ ]+", " ");
                   else
                        symbols = symbols.replaceAll(removeSymbols, "");
              symbols = symbols.trim();
              System.out.println(symbols);

  • Replacing characters in a string

    I have an application where a user can enter information into a webform. I'm using JSP, but of course the backend there is a Java function also.
    I am trying to write a function which will replace when the user hits enter with a <br> (break tag).
    Right now it's a complicated, messy loop to look at each character and it has many flaws.
    Is there a "replace" function that will do this for me?
    However, I don't think in a webpage form it transfers the \n end of line characters.

    Nope compiler error
    symbol : method replaceAll (java.lang.String,java.lang.String)
    location: class java.lang.String
    return (txt.replaceAll("\n","<br>"));

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

  • Parse a string to remove character

    Hi,
    Can you please help. I have a string like "1a" or "12c". Is there a way I can parse this to remove the character values, leaving "1" and "12"
    Many Thanks

    By using
    [url=http://java.sun.com/j2se/1.4.2/docs/api/java/lang
    /String.html#replaceAll(java.lang.String,
    java.lang.String)]String.replaceAll(String regex,
    String replacement)To remove all non-digit
    characters:replaceAll("\\D+", "");Or to remove all
    letters:replaceAll("\\p{L}+",
    "")(Check
    [url=http://java.sun.com/j2se/1.4.2/docs/api/java/util
    /regex/Pattern.html]Pattern doc if you want to
    refine it.)
    Also, you should note that String.replaceAll does not modify the Original string, it returns a NEW string with the modified value. A string is technically immutable.
    so you want the code to be something like:
    String cleanString = String.replaceAll( whichever pattern you choose );
    - Adam

  • Replace ever "anArray[1]" in a String...

    Hello, I want to replace all "anArray[1]" without quotes in a String like "int x = anArray[1]; int y = anArray[2]; int z = anArray[1] + anArray[2];"
    I tried this code:
    String s = "int x = anArray[1]; int y = anArray[2]; int z = anArray[1] + anArray[2];";
    s.replaceAll("anArray[1]", "1234");Though Java doesn't seem to replace anything...
    Any hints?

    The_Pointer wrote:
    s.replaceAll("anArray[1]", "1234");Java doesn't seem to replace anything...
    Any hints?[String.replaceAll()|http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29]
    Replaces each substring of this string that matches the given [regular expression|http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum] with the given replacement.
    In a regex "[" and "]" have special meaning - try "anArray\\[1\\]"(I know Encephalopathic already replied but the forum seems to mung double-backslash outside code blocks.)
    Also, Strings are immuable, so it
    Returns:
        The resulting String

  • How to cut string from output

    I have a program which will pullout the software list of a machine but in output it will display full path with software list buti need only softwarelist how to get it please help me
    try{
              String cmd = "reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\"";
                   //\Microsoft"+"\\Windows\\CurrentVersion\\Uninstall\"";
    // This one will show you software categories installed
    //String cmd = "reg query \"HKEY_LOCAL_MACHINE\\Software\"";
    Process p = Runtime.getRuntime().exec(cmd);
    Thread.sleep(200l); //terrible, the right way is p.waitFor
    //p.waitFor(); /* this command sometimes hangs on windows !!!???*/
    InputStream in = p.getInputStream();
    byte[] bytes = new byte[16384];
    StringBuffer buf = new StringBuffer();
    while(true) {
    int num = in.read(bytes);
    if(num == -1) break;
    buf.append(new String(bytes,0,num,"UTF-8"));
    System.out.println(buf.toString());
    output is:
    HKEY_LOCAL_MACHINE\SOFTWARE
    (Default) REG_SZ
    HKEY_LOCAL_MACHINE\SOFTWARE\Adobe
    HKEY_LOCAL_MACHINE\SOFTWARE\ahead
    HKEY_LOCAL_MACHINE\SOFTWARE\Alps
    HKEY_LOCAL_MACHINE\SOFTWARE\AMD
    HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation
    HKEY_LOCAL_MACHINE\SOFTWARE\ATI
    HKEY_LOCAL_MACHINE\SOFTWARE\ATI Technologies
    HKEY_LOCAL_MACHINE\SOFTWARE\Audible
    HKEY_LOCAL_MACHINE\SOFTWARE\AVG
    HKEY_LOCAL_MACHINE\SOFTWARE\AVG Security Toolbar
    HKEY_LOCAL_MACHINE\SOFTWARE\Azur

    The string class has a replaceAll method: http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29
    Juts replace "HKEY_LOCAL_MACHINE\SOFTWARE\" with "" (empty string).
    Timo

  • Remote white space from string

    Hi I need a method which will remove the spaces in a string eg "Hello World" -> "HelloWorld"
    I have the code below but it dosnt work for the obvious reason charAt() returns a char and im comparing to a string.
    Can anyone offer any help? Thanks
              public void removeSpace(String s)
              {     int rs = s.length();
                   String cat;
                   for (int i=0;i<rs;i++) {
                        cat = s.charAt(i).toString();
                        if (cat==" ") {
                             s.replace(""," ");
              }

    Hi I need a method which will remove the spaces in a
    string eg "Hello World" -> "HelloWorld"
    I have the code below but it dosnt work for the
    obvious reason charAt() returns a char and im
    comparing to a string.
    Can anyone offer any help? Thanks
              public void removeSpace(String s)
              {     int rs = s.length();
                   String cat;
                   for (int i=0;i<rs;i++) {
                        cat = s.charAt(i).toString();
                        if (cat==" ") {
                             s.replace(""," ");
    Hi,
    You can't modify the contents of a String, you must create a new String, and use that one. Your code should be:
    public String removeSpace(String s) {
        return s.replaceAll(" ", "");
    }The returned string is the string without spaces.
    /Kaj

  • Regex replaceAll question

    I am using replaceAll to replace a bunch of "tags" with content for this bit of software that I am porting (from something else) that creates documents (in the end) by populating templates with data.
    Here's my problem. The "tags" are all okay (not giving any regex content) but some of the data is. Because at first now I hit data that as a String has some regex funky characters in it. And regex got all all whiny about that because there aren't any matching groups. Well no. That's true.
    So I have to escape the $. But it occurs to me that I could well have more than this problem with other bits of content (including some parts I haven't gotten to yet) and I am wondering if there is any sort of easy solution. Is there way to tell replaceAll that the replacement String is a "literal" replacement i.e. I don't want any regex parsing at all just replace the found "tag" with the "content", that's it.
    Some sort of escape the whole sequence? Possibly. But I don't understand what it would be. \ is just for as single character?
    So any quick solution? Or alternative?
    BTW I am stuck with 1.4 on this project.

    yawmark wrote:
    I'd recommend trying Apache Commons StringUtils.
    Hope this message doesn't disappear into the aether.
    ~I think it did for awhile but like Lazarus arose...
    Anyway thank you for the effort.
    This is an interesting suggestion but I'd rather not go the route of adding more libraries.
    What I did at first was
    private void replaceAll(StringBuffer buff, String toFind, String toReplace){
      while(buff.indexOf(toFind)>-1){
         buff.replace(buff.indexOf(toFind),buff.indexOf(toFind)+toFind.length(),toReplace);
    }which worked good enough for me but someone else pointed out quoteReplacement and just doing my own version of that. Which works well too.
    Anyway thanks again I do appreciate it what with the current situation and all.

Maybe you are looking for

  • How do i sync my iphone with a new computer without losing all of my apps

    I bought a new macbook pro and want to sync my iphone and ipad with itunes on the new computer. I don't want to lose all of my apps (photos and music are already transfered). I am pretty sure that all of the apps that I have bought are in itunes, but

  • Both Desktop and Modern Versions answering incomin...

    Hi Folks I'm using Windows 10 and have both the desktop and modern versions of Skype installed. When an incoming call comes in, I answer it with the desktop version but then a few seconds into the call, the Modern App starts chiming and indicating th

  • Calendar enter query mode problem

    I have successfully implemented the calendar utility supplied by the demo. However, has anyone figured out how to use it when in enter-query mode? It doesn't work because you can't navigate out of current block when in enter_query mode.

  • Equate text to number

    Hi! I'm using Numbers version 3.2.2 I was wondering if there was a way to equate a text to a numerical value. For example if I  I write "sugar" in any given cell, Numbers sees it as -3. I'd like to be able to do sums of these things. For example (ima

  • About migrating security settings from embedded oc4j to preconfigured oc4j

    Hi, I was able to configure security in my 11g TP3 ADF application, and run it successfully against embedded oc4j. Now, when I want to migrate this to preconfigured oc4j, I am getting ERROR:null. Please see the steps I follow: set CLASSPATH=C:/JDevel