【问题标题】:Get an actual substring with Regex in c#在 C# 中使用正则表达式获取实际的子字符串
【发布时间】:2021-03-31 15:54:52
【问题描述】:

我有这个模式

@"($\w+)"

它会成功捕获 $substring 内的 long text $substring the rest of the text

但在某些情况下会失败,例如some string $sub.string the rest of string只会返回$sub

如何从字符串中获取实际的完整子字符串?

【问题讨论】:

  • 你可能有@"\$\w+",你想要\$\S+
  • @WiktorStribiżew 如果您发布完整回复,我可以将其标记为已解决。

标签: c# .net regex


【解决方案1】:

你可以使用

\$\S+

请参阅.NET regex demo

注意:如果您想去掉任何尾随标点符号(_ 除外),您可以在末尾添加 \b\$\S+\b

详情

  • \$ - 一个 $ 字符(需要转义,因为 $ 是断言字符串位置结束的特殊元字符)
  • \S+ - 任何一个或多个非空白字符。

在 C# 中,您可以使用

var output = Regex.Matches(text, @"\$\S+").Cast<Match>().Select(x => x.Value).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 2017-11-18
    • 2017-06-07
    • 2011-06-26
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多