c# - 提取字符串c#之间的所有重复子字符串
问题描述
有一个string s = "City, State, Country, City,State,Country"
并返回List<string>[0] = ["City, State, Country"] and List<string>[1] = ["City,State,Country"]
想过使用列表,但只返回第一个匹配的,它会在搜索第二个匹配的字符串时出错。有人可以帮我吗?感谢!
private static List<string> ExtractFromBody(string body, string start, string end)
{
List<string> matched = new List<string>();
int indexStart = 0;
int indexEnd = 0;
bool exit = false;
while (!exit)
{
indexStart = body.IndexOf(start);
if (indexStart != -1)
{
indexEnd = indexStart + body.Substring(indexStart).IndexOf(end);
matched.Add(body.Substring(indexStart + start.Length, indexEnd - indexStart - start.Length));
body = body.Substring(indexEnd + end.Length);
}
else
{
exit = true;
}
}
return matched;
}
解决方案
这是使用正则表达式有意义的一种情况。我假设提取应该区分大小写,如果不是,则RegexOptions.IgnoreCase
可以将选项Regex.Matches
作为第三个参数传递给方法。
public List<string> ExtractFromBody(string body, string start, string end) =>
Regex.Matches(body, $@"{start}.+?{end}")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
这会找到所有Regex
以开头start
和结尾的匹配项,end
然后转换为字符串列表。
在 LINQPad 中像这样使用它:
var s = "City, State, Country, abcd City, State, Country";
var start = "City";
var end = "Country";
ExtractFromBody(s,start,end).Dump();
输出是:
List<String> (2 items)
City, State, Country
City, State, Country
推荐阅读
- javascript - 远程方法未显示在环回 API 资源管理器中
- python-3.x - 使用python将多个表解析为一个csv
- spring-boot - springboot oauth如何验证access_token
- python - 无法使用 beautifulsoup3 从 json 脚本中提取所有 URL
- grails - 包含带有 g:include 的布尔参数作为字符串传递给包含的视图
- java - Maven:验证目标不会在自动化测试中打开浏览器
- plsql - 在字符串中分配 '
- php - C:\xampp\htdocs\org1\wp-settings.php 中没有这样的文件或目录
- unit-testing - Flutter/Dart 在单元测试中等待几秒钟
- kiwi-tcms - 由于 ssl 配置,我猜在使用 docker 运行 kiwi 后无法访问服务