[英]How to check if a string contains all of the characters of a word
I wish to check if a string contains a all of the characters of a word given, for example: 我想检查一个字符串是否包含给定单词的所有字符,例如:
var inputString = "this is just a simple text string";
And say I have the word: 并说我有这个词:
var word = "ts";
Now it should pick out the words that contains t and s : 现在应该选择包含t和s的单词:
this just string
这只是字符串
This is what I am working on: 这是我正在从事的工作:
var names = Regex.Matches(inputString, @"\S+ts\S+",RegexOptions.IgnoreCase);
however this does not give me back the words I like. 但这并没有给我回我喜欢的话。 If I had like just a character like t , it would give me back all of the words that contains t .
如果我只是喜欢一个像t这样的字符,它将把包含t的所有单词还给我。 If I had st instead of ts , it would give me back the word just .
如果我用st代替ts ,它将给我刚好这个词。
Any idea of how this can work ? 知道如何工作吗?
Here is a LINQ solution which is easy on the eyes more natural than regex. 这是一种LINQ解决方案,比正则表达式更自然,对眼睛更容易。
var testString = "this is just a simple text string";
string[] words = testString.Split(' ');
var result = words.Where(w => "ts".All(w.Contains));
The result is: 结果是:
this
这个
just只是
string串
You can use LINQ's Enumerable.All
: 您可以使用LINQ的
Enumerable.All
:
var input = "this is just a simple text string";
var token = "ts";
var results = input.Split().Where(str => token.All(c => str.Contains(c))).ToList();
foreach (var res in results)
Console.WriteLine(res);
Output: 输出:
// this
// just
// string
You can use this pattern. 您可以使用此模式。
(?=[^ ]*t)(?=[^ ]*s)[^ ]+
You can make regex dynamically. 您可以动态创建正则表达式。
var inputString = "this is just a simple text string";
var word = "ts";
string pattern = "(?=[^ ]*{0})";
string regpattern = string.Join("" , word.Select(x => string.Format(pattern, x))) + "[^ ]+";
var wineNames = Regex.Matches(inputString, regpattern ,RegexOptions.IgnoreCase);
Option without LINQ and Regex (just for fun): 没有LINQ和Regex的选项(只是为了好玩):
string input = "this is just a simple text string";
char[] chars = { 't', 's' };
var array = input.Split();
List<string> result = new List<string>();
foreach(var word in array)
{
bool isValid = true;
foreach (var c in chars)
{
if (!word.Contains(c))
{
isValid = false;
break;
}
}
if(isValid) result.Add(word);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.