0

i have a html file like below:(i'm new in regular expression pattern)

<a href=":$451$142">some thing</a>
<a href=":$14$15">some thing</a>                                
<a href=":$3$16">some thing</a>                     
<a href=":$312$17">some thing</a>

how can i replace all the ":$Number$Number" with "#"?

KF2
  • 9,887
  • 8
  • 44
  • 77

1 Answers1

0

This regex should work:

       String str = @"<a href="":$451$142"">some thing</a>  "+
                    @" <a href="":$14$15"">some thing</a>   "+                             
                    @" <a href="":$3$16"">some thing</a>    "+                 
                    @" <a href="":$312$17"">some thing</a>  ";
       String newStr = Regex.Replace(str,@":\$\d+\$\d+", "#");
       System.Console.WriteLine(str);
       System.Console.WriteLine("\n\n" + newStr);

It yields:

<a href=":$451$142">some thing</a>   <a href=":$14$15">some thing</a>    <a href
=":$3$16">some thing</a>     <a href=":$312$17">some thing</a>


<a href="#">some thing</a>   <a href="#">some thing</a>    <a href="#">some thin
g</a>     <a href="#">some thing</a>

The regular expression: :\$\d+\$\d+ will match any piece of text starting with a :, followed by a $ (the $ is a special character in regular expression language and thus needs to be escaped with an extra \ in front). The $ will in turn need to be followed by one or more digits (\d+) which in turn is followed by another : which is followed by one or more numbers (\d+). Please check this tutorial for more information.

Although in this case regular expressions did help, it is highly recommended that you do not use them to parse languages. Please use a dedicated framework such as HTML Agility Pack to do any HTML related processes. Take a look here for an example similar to what you seem to be trying to do.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • 1
    @irsog: No worries. However, if I where you, I would opt for the HTML Agility pack solution. HTML **should never** be processed by regular expressions. – npinti Jun 28 '12 at 07:26