Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Regex for replacing text in a string

Last post 02-04-2010, 10:58 AM by Sergei Z. 2 replies.
Sort Posts: Previous Next
  •  02-04-2010, 8:41 AM 59282

    Regex for replacing text in a string

    Hi everyone,

    I have very very little regex experience and I'm having big troubles with something I'm tryng to do.

    In Java I have for example a string "this is a string posted by @stev and I need @stev be clickable"

    What the regex should do is create a string like this :  "this is a string posted by <a href='stev'>@stev</a> and I need <a href='stev'>@stev</a> be clickable"

    Anyone got any idea how to do this? I have no idea, so any help is very welcome!

    Thanks!!

  •  02-04-2010, 10:09 AM 59283 in reply to 59282

    Re: Regex for replacing text in a string

    I don't know how I did it but I got it working. Also I have no idea what is happening.

    Here's my code:

     

            String text = "Blabla @stev visit the website http://www.google.com";
            System.out.println(text);
            Pattern p = Pattern.compile("@([_a-zA-Z]+)");
            StringBuffer sb = new StringBuffer(text.length());
            Matcher m = p.matcher(text);
            while (m.find()) {
                //String replacement = "<a href=\"http://link.html?user=$1\" target=\"_blank\">$0</a>";
                String replacement = "<a href=\"$1\">$0</a>";
                m.appendReplacement(sb, replacement);
            }
            m.appendTail(sb);
            text = sb.toString();
            System.out.println(text);

  •  02-04-2010, 10:58 AM 59286 in reply to 59283

    Re: Regex for replacing text in a string

    apparently you successfullly matched a target sring:

    @([_a-zA-Z]+)             --it matches @ste

    and then wrapped it in some text, arriving at the desired result:

    "<a href=\"$1\">$0</a>";

    where $1 is your matched string :

    @stev

View as RSS news feed in XML