【问题标题】:How to extract a string from a string between specific Chars in C#?如何从 C# 中特定字符之间的字符串中提取字符串?
【发布时间】:2021-12-04 18:22:43
【问题描述】:

我想从这些字符“@”和“#”之间的字符串中提取特定字符串。

例如我的字符串是

string myStr= "*-34@Apple#*-42@Banana#*-42@Orange#........";

我想从字符串中提取 Apple、Banana、Orange!

注意:我需要动态方法的解决方案,因为 myStr 长度可以是可变的

【问题讨论】:

标签: c#


【解决方案1】:

使用MatchCollection我们可以试试:

string myStr = "*-34@Apple#*-42@Banana#*-42@Orange#*........";
MatchCollection matches = Regex.Matches(myStr, "-\\d+@(.*?)#\\*");
Console.WriteLine("There were {0} matches:", matches.Count);
foreach (Match match in matches) {
    Console.WriteLine(match.Groups[1].Value);
}

打印出来:

There were 3 matches:
Apple
Banana
Orange

【讨论】:

  • 尊敬的@Tim 感谢您的回答,但请考虑字符串中的最后一个字符是 '#' 而不是 '*'
  • 例如,如果我的字符串是“-34@Apple#-42@Banana#*-42@Orange#”,它将跳过最后一个结果
  • 然后匹配-\d+@(.*?)#
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 2022-08-10
  • 1970-01-01
相关资源
最近更新 更多