问题
I have the following HTML as input:
<p>Hello</p>
<p>How are you?</p>
<div>Hello again</div>
How can I only output "Hello" from this? (only content from the first p-tag). And how can I also access only the second p-tag content?
So the output should be:
string p1 = "Hello"
string p2 = "How are you?"
My code so far. Full error!!! Help!
using System.Text.RegularExpressions;
string p1 = Regex.Match("<p>(.*?)</p>"[0], myString);
string p2 = Regex.Match("<p>(.*?)</p>"[1], myString);
回答1:
You could add an id="yourID" to each element then do a select like so:
Javascript:
let p1 = document.getElementById("element1").value
HTML:
<p id="element1"> </p>
回答2:
I think you might be looking for something like this:
Regex r = new Regex("<p>(.*?)<\\/p>");
string p1 = r.Matches(myString)[0].Groups[1].Value;
string p2 = r.Matches(myString)[1].Groups[1].Value;
The output looks like this:
Hello
How are you?
Keep in mind though this isn't the most bombproof method, iterating through the results might be useful to keep in mind going forward:
foreach (Match m in r.Matches(myString))
{
Console.WriteLine(m.Groups[1].Value);
}
来源:https://stackoverflow.com/questions/56050076/how-to-extract-content-from-p-html-tag