我怎样才能将其与正则表达式匹配?C#.

  • 本文关键字:正则表达式 c# .net
  • 更新时间 :
  • 英文 :


我想用正则表达式匹配 2 个字符串之间的所有内容。

输入文本如下所示:

 Back to previous › 



             › Send Message 
                             › Add as Buddy 
             › Add as Favorite 
             › Block this Person 


         People who like this (click to upvote) 

我想匹配"回到以前的>"和"喜欢这个的人"之间的所有内容(点击投票)。

我尝试了最简单的正则表达式,它(?<= Back to previous › ).*(?=People who like this profile (click to upvote) )但没有运气。

ideea 是捕获 2 行\字符串之间的所有内容,甚至认为您捕获的是换行符、制表符、字母数字等。

试试这个正则表达式:

(?<=Back\sto\sprevious.*?›).?(?=People\swho\slike\sthis)

string Input = @"Back to previous › 



         › Send Message 
                         › Add as Buddy 
         › Add as Favorite 
         › Block this Person 


     People who like this (click to upvote) ";
        foreach (Match M in Regex.Matches(Input, @"(?<=Backstosprevious.*?›).*?(?=Peopleswhoslikesthis)", RegexOptions.IgnoreCase | RegexOptions.Singleline))
        {
            MessageBox.Show(M.Value.Trim());
        }

这将在消息框中显示以下内容:

› Send Message 

                         › Add as Buddy 
         › Add as Favorite 
         › Block this Person

如果您确定将字符串分隔符(例如"Back to Previous")放在不同的行上,则没有理由使用正则表达式:

string text = /* Get Text */;
string lines = text.Split();
IEnumerable<string> content = lines.Skip(1).Take(lines.length - 2);

或者:

const string matchStart = "Back to previous >";
const string matchEnd = "People who like this (click to upvote)"
int beginIndex = text.IndexOf(matchStart) + matchStart.Length;
int endIndex = text.IndexOf(matchEnd);
string content = text.Substring(beginIndex, endIndex - beginIndex);

(我发布的代码未经测试,但它应该可以工作)

最新更新