Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c中使用正则表达式的字符串的特定值#_C#_Regex_Pattern Matching - Fatal编程技术网

C# c中使用正则表达式的字符串的特定值#

C# c中使用正则表达式的字符串的特定值#,c#,regex,pattern-matching,C#,Regex,Pattern Matching,我需要从给定的字符串中提取$value string text = "<h2 class="knownclass unknownclass1 unknownclass2" title="Example title>$Value </h2>" string text=“$Value.但我只需要$Value部分。 请告诉我。提前谢谢。正如我们多次说过的,使用正则表达式解析HTML或XML是不好的。忽略这一点,您捕获的内容太多了。这里有一个替代正则表达式应该可以工作 @"&l

我需要从给定的字符串中提取$value

string text = "<h2 class="knownclass unknownclass1 unknownclass2" title="Example title>$Value </h2>"
string text=“$Value.但我只需要$Value部分。

请告诉我。提前谢谢。

正如我们多次说过的,使用正则表达式解析HTML或XML是不好的。忽略这一点,您捕获的内容太多了。这里有一个替代正则表达式应该可以工作

@"<h2 class=""knownclass[^""]*"">(.*)</h2>"
@(.*

正如多次提到的,使用正则表达式解析HTML或XML是不好的。忽略这一点,您捕获的内容太多了。这里有一个替代正则表达式应该可以工作

@"<h2 class=""knownclass[^""]*"">(.*)</h2>"
@(.*

<代码> > p>假设字符串总是遵循此格式,请考虑下面的代码:

var index = text.IndexOf(">");
text.Substring(index + 1, text.IndexOf("<", index));
var index=text.IndexOf(“>”);

子字符串(index + 1,文本)IndexOf(“假设字符串总是遵循这个格式,考虑下面的代码:

var index = text.IndexOf(">");
text.Substring(index + 1, text.IndexOf("<", index));
var index=text.IndexOf(“>”);

子字符串(index + 1,文本)IndexOf(“如果它总是与您的字符串相同的模式,您可以考虑如下:

string text = "<h2 class=\"knownclass unknownclass1 unknownclass2\" title=\"Example title>$Value </h2>";
string result = "";

Regex test = new Regex(@"\<.*?\>(.*?)\</h2\>");
MatchCollection matchlist = test.Matches(text);

if (matchlist.Count > 0)
{
    for (int i = 0; i < matchlist.Count; i++)
    {
        result = matchlist[i].Groups[1].ToString();
    }
}
string text=“0)
{
for(int i=0;i
但如果您使用的是XML文件或HTML文件,我建议您使用XmlTextReader for XML和HtmlAgilityPack for HTML


希望它有帮助!

如果它总是与你的字符串相同的模式,你可以考虑如下:

string text = "<h2 class=\"knownclass unknownclass1 unknownclass2\" title=\"Example title>$Value </h2>";
string result = "";

Regex test = new Regex(@"\<.*?\>(.*?)\</h2\>");
MatchCollection matchlist = test.Matches(text);

if (matchlist.Count > 0)
{
    for (int i = 0; i < matchlist.Count; i++)
    {
        result = matchlist[i].Groups[1].ToString();
    }
}
string text=“0)
{
for(int i=0;i
但如果您使用的是XML文件或HTML文件,我建议您使用XmlTextReader for XML和HtmlAgilityPack for HTML


希望有帮助!

此字符串是否始终遵循此格式?您的文本是XML,在我看来,将其解析为XElement实例,然后提取元素的值将更容易、更快、更清晰。此字符串是否始终遵循此格式?您的文本是XML,在我看来,这将更容易、更快、更清晰rse将其插入XElement实例,然后提取元素的值。是的,非常感谢。如果字符“>”和$value之间存在未知空格,请告诉我该怎么做。例如,$value谢谢。:)我尝试了它,找到了解决方案Regex test=new Regex(@“\\s*(.*)\”);谢谢!可以,非常感谢。如果字符“>”和$value之间存在未知空格,请告诉我该怎么办。例如:$value谢谢。:)我试过了,找到了解决方案Regex test=new Regex(@“\\s*(.*)”);谢谢!