• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 456
  • Last Modified:

regex expression c#

I have a string in c# and i need a regex solution to get all matches.
An example string is:

  <h1>$/information_page/paragraphtitle$</h1>
            <div class="maintext">
                 $/information_page/paragraphmaintext$
            </div>

I need to have all the items which start with "$/" and end with "$" so in this example "/information_page/paragraphtitle" and "/information_page/paragraphmaintext".

The items can be inside a text (not separated by spaces) and all kind of characters (a-z,0-9,/ and _) can be inside. In between the two delimeters are no spaces allowed (not necessary in regex)

Thanks
0
Rovi31
Asked:
Rovi31
  • 2
1 Solution
 
brutaldevCommented:
The pattern to match the strings as requested is:  
\$/.*\$

Open in new window


The code to iterate the matches would be:

 
using System.Text.RegularExpressions;

...

foreach (Match match in Regex.Matches(yourHtmlString, @"\$/.*\$", RegexOptions.IgnoreCase))
{
  string val = match.Value;
  // Do something with you matched strings.
}

...

Open in new window

0
 
käµfm³d 👽Commented:
\$/.*\$

That pattern is dangerous. If we were to modify the sample input a bit:
<h1>$/information_page/paragraphtitle$</h1><div class="maintext">$/information_page/paragraphmaintext$</div>

Open in new window


That is, make it one whole line (no line breaks), then the result you would actually get would be:
$/information_page/paragraphtitle$</h1><div class="maintext">$/information_page/paragraphmaintext

Open in new window


I'm sure that's probably not what you want. The safer route would be something like:
\$/[^$]*\$

Open in new window


string input = @"<h1>$/information_page/paragraphtitle$</h1>
                    <div class=""maintext"">
                         $/information_page/paragraphmaintext$
                    </div>";

MatchCollection matches = Regex.Matches(input, @"\$/[^$]*\$");

foreach (Match m in matches)
{
    Console.WriteLine(m.Value);
}

Console.ReadKey();

Open in new window

0
 
käµfm³d 👽Commented:
My "output" from the "bad" regex should have included a trailing "$". Copy/paste didn't show me any love on that one  : )
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now