Reputation: 21960
I want to extract the strings like aaa.a1
and aaa.a2
from my list. All this strings contain "aaa."
.
How can I combine Regex with Linq?
var inputList = new List<string>() { "bbb aaa.a1 bbb", "ccc aaa.a2 ccc" };
var result = inputList.Where(x => x.Contains(@"aaa.")).Select(x => x ???? ).ToList();
Upvotes: 2
Views: 98
Reputation: 37367
You could try slight different solution:
var result = inputList
.Where(i => Regex.Match(i, @"\baaa\.[a-z0-9]+")?.Success)
// or even
// .Where(i => Regex.Match(i, @"\ba+\.[a-z0-9]+")?.Success)
Upvotes: 2
Reputation: 626794
You may use
var inputList = new List<string>() { "bbb aaa.a1 bbb", "ccc aaa.a2 ccc" };
var result = inputList
.Select(i => Regex.Match(i, @"\baaa\.\S+")?.Value)
.Where(x => !string.IsNullOrEmpty(x))
.ToList();
foreach (var s in result)
Console.WriteLine(s);
Output:
aaa.a1
aaa.a2
See C# demo
The Regex.Match(i, @"\baaa\.\S+")?.Value
part tries to match the following pattern in each item:
\b
- a word boundary aaa\.
- an aaa.
substring\S+
- 1+ non-whitespace chars.The .Where(x => !string.IsNullOrEmpty(x))
will discard empty items that result from the items with no matching strings.
Upvotes: 3