将正则表达式匹配项转换为字符串列表

编程入门 行业动态 更新时间:2024-10-27 22:26:29
本文介绍了将正则表达式匹配项转换为字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正试图在大约5万个字符串的大列表中找到相等的子字符串,这很好:

I'm trying to find equal sub-string in big list about 50 000 strings, this way fine:

var results = myList.FindAll(delegate (string s) { return s.Contains(myString); });

但是它还会查找带有单词一部分的子字符串,例如,如果我正在寻找"you do",它还会发现额外的"you dont",因为其中包含"you do ..".

but it also looks for sub-string with part of word, for example, if I'm looking for "you do" it founds also extra "you dont" because contains "you do..".

因此,我对上一个问题的答案应该可以用根据我的需要,但是我不确定如何从正则表达式匹配中获取特定代码的字符串列表:

So, this answer to my previous question supposedly should work as i need, but I'm not sure, how to get strings list from regex matches for particular code:

foreach (string phrase in matchWordsList) { foreach (string str in bigList) { string[] stringsToTest = new[] { phrase }; var escapedStrings = stringsToTest.Select(s => Regex.Escape(s)); var regex = new Regex("\\b(" + string.Join("|", escapedStrings) + ")\\b"); var matches = regex.Matches(str); foreach (string result in matches) /// Incorrect: System.InvalidCastException { resultsList.Add(result); } } }

直接从matches获取字符串到list会引发异常:

Getting strings from matches directly to the list throws exception:

发生类型为'System.InvalidCastException'的未处理的异常 在test.exe中

An unhandled exception of type 'System.InvalidCastException' occurred in test.exe

其他信息:无法转换类型的对象 "System.Text.RegularExpressions.Match"键入"System.String".

Additional information: Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.String'.

所以,我正在尝试找出将var matches = regex.Matches(str);转换为列表的方法

So, I'm trying to figure out, hot to convert var matches = regex.Matches(str); to the list

推荐答案

您可以使用linq做到这一点.但是,您需要先Cast,然后再Select

You can do it with linq. However you will need to Cast it first then Select

var resultsList = regex.Matches(str) .Cast<Match>() .Select(m => m.Value) .ToList();

someList.AddRange( regex.Matches(str) .Cast<Match>() .Select(m => m.Value));

更多推荐

将正则表达式匹配项转换为字符串列表

本文发布于:2023-11-05 09:01:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560421.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   转换为   列表   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!