我需要从字符串中获取所有子字符串.
例如:
StringParser.GetSubstrings("[start]aaaaaa[end] wwwww [start]cccccc[end]", "[start]", "[end]");
Run Code Online (Sandbox Code Playgroud)
返回2个字符串"aaaaaa"和"cccccc"假设我们只有一个级别的嵌套.不确定regexp,但我认为它会有用.
Jak*_*ake 33
private IEnumerable<string> GetSubStrings(string input, string start, string end)
{
Regex r = new Regex(Regex.Escape(start) + "(.*?)" + Regex.Escape(end));
MatchCollection matches = r.Matches(input);
foreach (Match match in matches)
yield return match.Groups[1].Value;
}
Run Code Online (Sandbox Code Playgroud)
这是一种不使用正则表达式且不考虑嵌套的解决方案。
public static IEnumerable<string> EnclosedStrings(
this string s,
string begin,
string end)
{
int beginPos = s.IndexOf(begin, 0);
while (beginPos >= 0)
{
int start = beginPos + begin.Length;
int stop = s.IndexOf(end, start);
if (stop < 0)
yield break;
yield return s.Substring(start, stop - start);
beginPos = s.IndexOf(begin, stop+end.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18030 次 |
| 最近记录: |