我有一个这样的字符串:解析字符串与正则表达式
Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323
对于那些谁没有注意到,我想保持文本始终是/D
和/p
之间。 我试图解析它使用正则表达式,但我不能这样做的所有字符串。 它始终保持第一个或最后一个单词。
如何保留一个新的字符串,其中包含/D
和/p
之间的所有单词?
预期输出:
hello good
我有一个这样的字符串:解析字符串与正则表达式
Addadafafa/DHello/p2324141142DsddDsdsds/Dgood/p23323
对于那些谁没有注意到,我想保持文本始终是/D
和/p
之间。 我试图解析它使用正则表达式,但我不能这样做的所有字符串。 它始终保持第一个或最后一个单词。
如何保留一个新的字符串,其中包含/D
和/p
之间的所有单词?
预期输出:
hello good
试试这个:
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);
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.
var result = input.Split(new[] {"/D", "/p"},
StringSplitOptions.RemoveEmptyEntries)
.Where((w, i) => (i & 1) == 1);
这里的关键是,非贪婪量词'+? '。没有它,它会匹配'Hello/p2324141142DsddDsdsds/Dgood'。 –