How to check if a string contains all characters of a word

I want to check if a string contains all the characters of a given word, for example:

var inputString = "this is just a simple text string"; 

And I will say that I have a word:

 var word = "ts"; 

Now he should select the words containing t and s :

just a string

This is what I'm working on:

 var names = Regex.Matches(inputString, @"\S+ts\S+",RegexOptions.IgnoreCase); 

however, this does not return to me the words that I like. If I had the same character as t , he would return to me all the words containing t . If I had st instead of ts , he would return the word just to me.

Any idea on how this might work?

+6
source share
4 answers

Here is a LINQ solution that is easy on the eyes more natural than regular expression.

 var testString = "this is just a simple text string"; string[] words = testString.Split(' '); var result = words.Where(w => "ts".All(w.Contains)); 

Result:

this is
just
line

+10
source

You can use 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 
+7
source

You can use this template.

 (?=[^ ]*t)(?=[^ ]*s)[^ ]+ 

Dynamic dynamic expression.

 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); 
+6
source

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); } 
+3
source

All Articles