【问题标题】:Regex on string with dots带点的字符串上的正则表达式
【发布时间】:2019-12-20 12:34:46
【问题描述】:

我有以下字符串:

root.single_product.baby->teenager_furn.others.

我想提取 .-sign 前面的每个字符串。我想出了这个:

Regex.Matches("root.single_product.baby->teenager_furn.others.", @"([\w]+)");

这给了我以下列表:

root
single_product
baby
teenager_furn
others

但我想要以下内容:

root
single_product
baby->teenager_furn
others

我怎样才能做到这一点?

【问题讨论】:

  • 我很确定您正在寻找 Regex.Split 或普通的 string.Split 函数。
  • @mypronounismonicareinstate 模式应该如何?
  • @Bryan 使用模式\. 表示Regex.Split 或仅使用字符. 表示string.Split
  • @Bryan 'string [] split = myString.Split('.');'

标签: c# regex


【解决方案1】:

您当前的正则表达式匹配“所有单词字符”。 -> 不是单词字符,因此它们不匹配。您的正则表达式似乎没有说太多关于匹配 before 点的内容。如果您希望它像这样保持非常宽松,您可以执行以下操作之一:

  • 单词字符,还有->

    [\w->]+
    
  • 所有不是点的东西:

    [^.]+
    

如果您想要一个严格匹配点之前的内容的正则表达式,您可以执行以下操作:

[^.]+(?=\.)

([^.]+)\.

并提取第 1 组。

【讨论】:

    【解决方案2】:

    使用 Regex 对您来说很重要吗?为什么不使用 string.Split 方法?这是示例:https://dotnetfiddle.net/HQgFwm

    或者您可以使用带有模式“(.)”的 Regex.Split,如https://dotnetfiddle.net/y6AGVY

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多