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 :
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 . If I had st instead of ts , it would give me back the word just .
Any idea of how this can work ?
Here is a LINQ solution which is easy on the eyes more natural than regex.
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
:
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):
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.