反转正则表达式匹配
时间:2020-03-06 14:42:44 来源:igfitidea点击:
我将如何反转.NET正则表达式匹配项?我只想提取匹配的文本,例如我想从HTML文件中提取所有IMG标签,但仅提取图像标签。
解决方案
这与反转Regexp无关。只需搜索相关的文本并将其放在一个组中即可。
不明白你的意思。我们是在谈论捕获团体吗?
我和David H.在一起:反转表示我们不希望匹配,而是匹配周围的文本,在这种情况下,Regex方法Split()将起作用。这就是我的意思:
static void Main(string[] args) { Regex re = new Regex(@"\sthe\s", RegexOptions.IgnoreCase); string text = "this is the text that the regex will use to process the answer"; MatchCollection matches = re.Matches(text); foreach(Match m in matches) { Console.Write(m); Console.Write("\t"); } Console.WriteLine(); string[] split = re.Split(text); foreach (string s in split) { Console.Write(s); Console.Write("\t"); } }