[英]What's the best way to acquire a list of strings that match a string inside a string, by looking through a string list?
Basically I have a string array that I am using to match inside a single string:基本上我有一个字符串数组,我用它来匹配单个字符串:
string[] matches = { "{A}", "{B}", "{CC}" };
Then I from these I look if I find any of these inside my string:然后我从这些中查找是否在我的字符串中找到任何这些:
string text = "Lorem Ipsum is {CC} simply dummy text {A} of the {CC} printing and typesetting industry {B}."
In which case, the resulting array I want to gather should be:在这种情况下,我想要收集的结果数组应该是:
string[] allmatches = { "{CC}", "{A}", "{CC}", "{B}" };
Is there an easy way to do this using LINQ or maybe Regex?有没有一种简单的方法可以使用 LINQ 或正则表达式来做到这一点?
Assuming, that {A}..{Z}
are the only matches required, we can try combining Regex
and Linq, eg假设
{A}..{Z}
是唯一需要的匹配项,我们可以尝试结合Regex
和 Linq,例如
string text =
@"Lorem Ipsum is {C} simply dummy text {A} of the {C} printing and typesetting industry {B}.";
string[] allmatches = Regex
.Matches(text, @"\{[A-Z]\}")
.Cast<Match>()
.Select(m => m.Value)
//.Where(item => matches.Contains(item)) // uncomment to validate matches
.ToArray();
Let's have a look:我们来看一下:
Console.Write(string.Join(", ", allmatches));
Outcome:结果:
{C}, {A}, {C}, {B}
Edit: uncomment .Where(...)
if you want matches which are in matches[]
only编辑:取消注释
.Where(...)
如果您只想要匹配项中的matches[]
Edit 2: If match doesn't necessary contain one letter only, change pattern:编辑 2:如果匹配不需要只包含一个字母,请更改模式:
.Matches(text, @"\{[A-Z]+\}") // one or more capital letters
.Matches(text, @"\{[a-zA-Z]+\}") // one or more English letters
.Matches(text, @"\{\p{L}+\}") // one or more Unicode letters
.Matches(text, @"\{[^}{]+\}") // one or more characters except "{" and "}"
Construct the regex by first Escape
ing each element in matches
using Select
, then Join
ing with |
通过首先使用
Select
对matches
中的每个元素进行Escape
,然后使用Join
来构造正则|
. . After that, get the
Matches
of the regex against text
and Select
the Value
s:之后,获取正则表达式对
text
的Matches
项和Select
的Value
:
var regex = string.Join("|", matches.Select(Regex.Escape));
var result = Regex.Matches(text, regex)
.Cast<Match>()
.Select(x => x.Value).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.