[英]How can I match this with a regex ? C#
我想用正则表达式匹配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\\)\\ )
但没有运气用它。
想法是捕获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, @"(?<=Back\sto\sprevious.*?›).*?(?=People\swho\slike\sthis)", RegexOptions.IgnoreCase | RegexOptions.Singleline))
{
MessageBox.Show(M.Value.Trim());
}
在消息框中显示以下内容:
› Send Message
› Add as Buddy
› Add as Favorite
› Block this Person
如果确定在不同的行上都有字符串定界符(例如,“返回上一步”),则没有理由使用正则表达式:
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);
(我发布的代码未经测试,但可以正常工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.