-2

I have the following pattern:

    private const string _usernamePattern = "Username: <strong>.*</strong>";

and code:

    private string Grab(string text, string pattern)
    {
        Regex regex = new Regex(pattern);
        if (!regex.IsMatch(text))
            throw new Exception();
        else
            return regex.Match(text).Value;

    }

so, it works fine for string like:

Username: <strong>MyUsername</strong>

But I need grab only MyUsername, without <strong> tags. How to do it?

Oleg Sh
  • 8,496
  • 17
  • 89
  • 159
  • Possible duplicate of https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – TheGeneral Mar 04 '19 at 03:02

2 Answers2

2

You shouldn't really be doing this with regex and you should use a dedicated html parser..

See this question as to why

RegEx match open tags except XHTML self-contained tags

However, if this is an extremely limited case and not lumps of html, and all you want is the text between two tags, you could just use the following pattern...

  • Zero-width positive lookbehind assertion
  • Zero-width positive lookahead assertion
(?<=<strong>).*?(?=</strong>)

enter image description here

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

Try:

private const string _usernamePattern = "Username: <strong>(?<Email>.*)</strong>";
...
private string Grab(string text, string pattern)
{
    var match = Regex.Match(text, pattern);

    if (!match.Success)
        throw new Exception();
    else
        return match.Groups["Email"].Value;
}
yv989c
  • 1,453
  • 1
  • 14
  • 20