[英]Parsing string with regex
我有一个像这样的字符串:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.