Reputation: 4443
I have a List<string>
with some words.
I want to get all of elements, witch contains letters in this schema:
a00b0c000d
- 0
is random char, a,b,c,d
- are constantly chars in string.
How can I do this? Can I do this only with Regex? There isn't any other solution?
Upvotes: 6
Views: 3040
Reputation: 22794
Well, you can do it with Regex and LINQ:
Regex yourRegex = new Regex(@"a..b.c...d");
//if you want whole string match use ^a..b.c...d$
var result = yourList.Where(yourRegex.IsMatch);
Upvotes: 2
Reputation: 69372
An efficient way would be to just iterate over the list.
List<string> matches = new List<string>();
myList.ForEach((x) => { if(x[0] == 'a' && x[3] == 'b' && x[5] == 'c' && x[9] == 'd') matches.Add(x); });
Or you can use LINQ which might be slightly slower but unlikely to be a bottleneck.
var matches = myList.Where(x => x[0] == 'a' && x[3] == 'b' && x[5] == 'c' && x[9] == 'd').ToList();
Upvotes: 1
Reputation: 9458
You can use IndexOfAny()
method for string after looping through List.IndexOfAny
searches a string for many values.
List<string> words = new List<string>();
foreach(string word in words)
{
int match = word.IndexOfAny(new char[] {'a', 'b', 'c', 'd'});
if(match!=-1)
{
//Processing Logic here
}
}
Upvotes: 1
Reputation: 3833
Without using Regex, you could probably do something along the lines of
List<string> stromgs = new List<string>();
foreach (var s in stromgs)
{
var sa = s.Select(c => c.ToString(CultureInfo.InvariantCulture)).ToArray();
if (sa.Contains("a") && sa.Contains("b") && sa.Contains("c") && sa.Contains("d"))
yield return s;
}
To get the results you are after. I haven't profiled this code so it could be a lot slower than using regular expressions for all I know, but it should give you a way to avoid Regex altogether (which is something I usually tend to do).
Upvotes: 0
Reputation: 51634
Well, instead of a regex you can use LINQ to check for specific characters in the respective positions. But I'd definitely prefer a regular expression.
var result = yourList
.Where(x => x[0] == "a")
.Where(x => x[3] == "b")
.Where(x => x[5] == "c")
.Where(x => x[9] == "d")
.ToList();
Upvotes: 5