C#在两个字符串之间获取字符串

C#在两个字符串之间获取字符串,c#,regex,string,ads,C#,Regex,String,Ads,我从谷歌广告中生成了以下脚本: <!-- HomePage_468x60 --> <div id='div-gpt-ad-1383121038726-0' style='width:468px; height:60px;'> <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-

我从谷歌广告中生成了以下脚本:

        <!-- HomePage_468x60 -->
        <div id='div-gpt-ad-1383121038726-0' style='width:468px; height:60px;'>
        <script type='text/javascript'>
        googletag.cmd.push(function() { googletag.display('div-gpt-ad-1383121038726-0'); });
        </script>
        </div>

googletag.cmd.push(函数(){googletag.display('div-gpt-ad-1383121038726-0');});
我试图为自己提取一些相关数据,比如广告名称、广告大小和广告Id(这样我就可以为head标签呈现脚本)

尝试使用一些正则表达式,如下所示:

public static String GetTextBetween(string source, string leftWord, string rightWord)
{

    return
        Regex.Match(source, String.Format(@"{0}\s(?<words>[\w\s.:]+)\s{1}", leftWord, rightWord),
                    RegexOptions.IgnoreCase).Groups["words"].Value;
}
公共静态字符串GetTextBetween(字符串源、字符串leftWord、字符串rightWord)
{
返回
Regex.Match(源,String.Format(@“{0}\s(?[\w\s.:]+)\s{1}”、leftWord、righword),
RegexOptions.IgnoreCase)。组[“单词”]。值;
}
其中,我发送函数脚本和一个左单词和一个右单词,例如,为了获得广告名,我将发送:

GetTextBetween(ad, "<!-- ", " -->");
GetTextBetween(ad,”);
但是它返回一个空字符串

谁能帮帮我吗?还是有人有更好的方法

编辑

我想我会对每个匹配使用seporate正则表达式,但是我找不到正确的表达式来获取这个字符串
div-gpt-ad-1383121038726-0

从字符串中,有人能帮上忙吗?

如果要使用regex,我不会使用helper“getTextBevering”函数。我只会在每种情况下写一个正则表达式。但是,如果您想使用它,那么在特殊字符方面会有一些问题(因为对于leftString和rightString,您希望准确地找到它们,并且其中没有任何特殊符号会被视为正则表达式的一部分。)leftWord和rightWord需要为正则表达式转义一些字符。我用这样的方式:

  private static string EscapeCharsForRegularExpression( string s )
  {
     //note that we must replace the \ first, because the following statements add backslashes
     return s.Replace( "\\", "\\\\" ).Replace( ".", "\\." ).Replace( "(", "\\(" ).Replace( ")", "\\)" ).Replace( "<", "\\<" ).Replace( "[", "\\[" ).Replace( "]", "\\]" ).Replace( ">", "\\>" ).Replace( "{", "\\{" ).Replace( "}", "\\}" ).Replace( "*", "\\*" ).Replace( "^", "\\^" ).Replace( "+", "\\+" ).Replace( ":", "\\:" );
  }
哦。。。这个正则表达式为您提供了第一个匹配项:

Regex.Matches( inputString, @"<!--\s*(.+?)\s*-->", RegexOptions.None )[0].Groups[1].Value;
适用于:div-gpt-ad-1383121038726-0(周围无撇号)


将其解析为xml,而不是试图使用正则表达式。谢谢您的回复。但是您编写的用于转义字符串的函数没有帮助。第一场比赛的正则表达式效果很好,我想我会在每场比赛中使用一个正则表达式。谢谢,请帮我使用正确的正则表达式,以便从字符串中获取此“div-gpt-ad-1383121038726-0”?
Regex.Matches( inputString, @"<!--\s*(.+?)\s*-->", RegexOptions.None )[0].Groups[1].Value;
Regex.Matches( inputString, @"'.*?'", RegexOptions.None )[0].Groups[0].Value;
Regex.Matches( inputString, @"'(.*?)'", RegexOptions.None )[0].Groups[1].Value;