-3

I have been trying to get the id from the following text

<body id=\"body\" runat=\"server\"> 

In C# using substring or even Regex, but nothing seems to be working. No matter what regex i use, i always get the whole line back. I have been trying to use ^id, ^id.*, ^id=\\\\\\\\.* and id=.* but they don't either work or give me the desired output. Is there any way i can get the id portion from this text which is enclosed between the characters \" "\?

The Scientific Method
  • 2,374
  • 2
  • 14
  • 25
user8657231
  • 67
  • 1
  • 8
  • 2
    Take a moment to read through the [editing help](//stackoverflow.com/editing-help) in the help center. Formatting on Stack Overflow is different than other sites. The better your post looks, the easier it is for others to read and understand it. – gunr2171 Aug 15 '18 at 13:47
  • 1
    Ban hammer a bit much... but [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/q/1732348/1324033) – Sayse Aug 15 '18 at 13:49
  • 5
    As noted in the regex tag - "NOTE: Asking for HTML, JSON, etc. regexes tends to be met with negative reactions. If there is a parser for it, use that instead." – Sayse Aug 15 '18 at 13:49
  • is it not possible even if you convert HTML into a simple text and make it look like a string like " body id=\"body\" runat=\"server\" "? and then try to use regex over this string – user8657231 Aug 15 '18 at 13:59
  • https://stackoverflow.com/questions/10709821/find-text-in-string-with-c-sharp – Slai Aug 15 '18 at 14:08
  • There is not string between \" and "\! – kame Aug 15 '18 at 19:20

1 Answers1

1

Try this:

        string htmlString = "<body id=\"body\" runat=\"server\">";

        Regex regex = new Regex("id=\"(.*?)\"");
        Match m = regex.Match(htmlString);
        Group g = m.Groups[1];
        string id = g.ToString();

        Console.WriteLine(id); //body

Test here: http://rextester.com/BQSF93427

Laurianti
  • 903
  • 1
  • 5
  • 19