从字符串中提取多个空格
本文关键字:空格 提取 字符串 | 更新日期: 2023-09-27 18:10:50
我想要得到长度大于1个空格的空白
下面的代码为我提供了每个字母之间的空字符,以及空白。但是,我只想提取c
和d
之间的两个空白字符串,以及f
和g
之间的3个空白字符串。
string b = "ab c def gh";
List<string> c = Regex.Split(b, @"[^'s]").ToList();
更新:下面的工作,但我正在寻找一个更优雅的方式来实现这一点:
c.RemoveAll(x => x == "" || x == " ");
期望的结果将是包含" "
和" "
的List<string>
如果你想要List<String>
作为结果,你可以执行这个Linq查询
string b = "ab c def gh";
List<String> c = Regex
.Matches(b, @"'s{2,}")
.OfType<Match>()
.Select(match => match.Value)
.ToList();
这应该是你想要的列表。
string b = "ab c def gh";
var regex = new Regex(@"'s's+");
var result = new List<string>();
foreach (Match m in regex.Matches(b))
result.Add(m.Value);
如果您对这些空格组感兴趣,您可以使用
foreach(var match in Regex.Matches(b, @"'s's+")) {
// ... do something with match
}
这保证你将匹配至少2个空格。
而不是使用Regex分割,尝试使用Regex.Matches
来获得与您的模式匹配的所有项目-在这种情况下,我使用了一个模式来匹配两个或多个空白字符,我认为这是你想要的?
var matchValues = Regex.Matches("ab c def gh", "''s''s+")
.OfType<Match>().Select(m => m.Value).ToList();
令人恼火的是,Regex.Matches
返回的MatchCollection
不是IEnumerable<Match>
,因此需要在LINQ表达式中使用OfType<>
。
您可以使用以下单行:
var list =Regex.Matches(value,@"[ ]{2,}").Cast<Match>().Select(match => match.Value).ToList();