我有一个这样的字符串:
Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323
对于那些没有注意到的人,我想保留的文字总是介于/D
和之间/p
。我尝试使用正则表达式对其进行解析,但无法对所有字符串进行解析。它总是保留第一个或最后一个词。
如何保留一个新字符串,其中包含前一个字符串之间的所有/D
单词/p
?
预期输出:
hello good
string input = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
var parts = Regex.Matches(input, "/D(.+?)/p")
.Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
string finalStr = String.Join(" ", parts); //If you need this.
试试这个:
string str = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
Regex reg = new Regex(@"/D(\w+)/p");
MatchCollection matches = reg.Matches(str);
string result = "";
foreach (Match match in matches)
{
result += match.Result("$1") + " ";
}
Console.WriteLine(result);
或者:
string str = "Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323";
Regex reg = new Regex(@"(?!/D)[^D]\w+(?=/p)");
MatchCollection matches = reg.Matches(str);
string result = "";
foreach (Match match in matches)
{
result += match.Value + " ";
}
Console.WriteLine(result);
var result = input.Split(new[] {"/D", "/p"},
StringSplitOptions.RemoveEmptyEntries)
.Where((w, i) => (i & 1) == 1);