Linq语句来获取不是较长字符串的子字符串的字符串
本文关键字:字符串 语句 获取 Linq | 更新日期: 2023-09-27 18:16:19
我有一个长字符串S,可能包含模式p1, p2, p3, ....;
所有图案都放在MatchCollection
对象中
我想做一些类似的事情
string ret=p_n if !(S.Contains(p_n))
我写了一个for循环来做这个
foreach(string p in PatternList)
{
s=(!S.contain(p.valus))?p.value:"";
}
我想知道一个LINQ声明,让我的代码更可爱。
var patterns = new List<string> { "one", "two", "three" };
var misses = patterns.Where(s => !longString.Contains(s));
class Program
{
static void Main(string[] args)
{
string S = "12345asdfasdf12w3e412354w12341523142341235123";
string patternString = "one1234554321asdf";
MatchCollection p_ns = Regex.Matches(patternString, "one|12345|54321|asdf");
var nonMatches = (from p_n in p_ns.Cast<Match>()
where !S.Contains(p_n.Value)
select p_n.Value);
foreach (string nonMatch in nonMatches)
{
Console.WriteLine(nonMatch);
}
Console.ReadKey();
}
}
或者,要使用贾斯汀的答案,你也可以使用下面的变体。
class Program
{
static void Main(string[] args)
{
string S = "12345asdfasdf12w3e412354w12341523142341235123";
string patternString = "one1234554321asdf";
MatchCollection p_ns = Regex.Matches(patternString, "one|12345|54321|asdf");
var nonMatches = p_ns.Cast<Match>().Where(s => !S.Contains(s.Value));
foreach (Match nonMatch in nonMatches)
{
Console.WriteLine(nonMatch.Value);
}
Console.ReadKey();
}
}
static void Main(string[] args)
{
string S = "p1, p2, p3, p4, p5, p6";
List<string> PatternList = new List<string>();
PatternList.Add("p2");
PatternList.Add("p5");
PatternList.Add("p9");
foreach (string s in PatternList.Where(x => !S.Contains(x)))
{
Console.WriteLine(s);
}
Console.ReadKey();
}