[英]How can I match this with a regex ? C#
I wanna match with a regex everything between 2 strings. 我想用正则表达式匹配2个字符串之间的所有内容。
The input text is like this: 输入文本如下:
Back to previous ›
› Send Message
› Add as Buddy
› Add as Favorite
› Block this Person
People who like this (click to upvote)
I wanna match everything between Back to previous > and People who like this (click to upvote) . 我想匹配“ 返回上一个>”和“ 喜欢此人的人”之间的所有内容(单击以投票) 。
I tried the easiest regex which is (?<=\\ Back\\ to\\ previous\\ ›\\ ).*(?=People\\ who\\ like\\ this\\ profile\\ \\(click\\ to\\ upvote\\)\\ )
but no luck with it. 我尝试了最简单的正则表达式
(?<=\\ Back\\ to\\ previous\\ ›\\ ).*(?=People\\ who\\ like\\ this\\ profile\\ \\(click\\ to\\ upvote\\)\\ )
但没有运气用它。
The ideea is to catch everything between 2 lines\\strings, even thought what you catch is newline, tab, alphanumeric, and so on. 想法是捕获2行\\字符串之间的所有内容,甚至认为捕获的内容是换行符,制表符,字母数字等。
Try this Regex: 试试这个正则表达式:
(?<=Back\\sto\\sprevious.*?›).?(?=People\\swho\\slike\\sthis) (?<= 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());
}
This displays following in the message box: 在消息框中显示以下内容:
› Send Message
› Add as Buddy
› Add as Favorite
› Block this Person
If you are sure you have your string delimiters (eg "Back to Previous") on different lines you have no reason of using Regexes: 如果确定在不同的行上都有字符串定界符(例如,“返回上一步”),则没有理由使用正则表达式:
string text = /* Get Text */;
string lines = text.Split();
IEnumerable<string> content = lines.Skip(1).Take(lines.length - 2);
Or alternatively: 或者:
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);
(The code I've posted is not tested but it should work) (我发布的代码未经测试,但可以正常工作)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.