【问题标题】:create a rule for more than one use inside a regex call在正则表达式调用中创建用于多次使用的规则
【发布时间】:2011-09-19 12:20:45
【问题描述】:

假设我有以下文本:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod ,,,,,,tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam, quis ,,,,,nostrud exercitation ullamco [,] laboris nisi ut aliquip ex ea commodo consequat。 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu [,,,,,] fugiat nulla pariatur。 Exceptioneur sint {,,}occaecat cupidatat non proident, sunt {,,,,,} in culpa qui officia deserunt mollit anim id ,,,,,est laborum。

我想用以下模式选择文本中的所有逗号

(\,{2,99})

但我还想指定仅在特定字符之间应用相同的过滤器,例如仅选择 []{} 之间的逗号,但不选择 [}

这会失败的地方:

(\[|\{)  (\,{2,99})  (\]|\})

以下将按预期工作

(\{)  (\,{2,99})  (\})  |  (\[)  (\,{2,99})  (\])

所以问题是每次我想用另一个选择包围这个匹配时,我都必须重新输入(\,{2,99})

有什么方法可以在同一命令中声明 variable 以便以后应用?喜欢:

$1=(\,{2,99}) | (\{$1\}) | (\[$1\])

我希望这很容易理解,请多多包涵,因为定期体验对我来说确实是一个新事物,所以所有这些声明对你来说可能看起来很糟糕:)

如果您能注意到这里写得不好并推荐一种更好的方法,我将不胜感激。

还请注意,这个捕获所有逗号的示例是为了说明我想如何在同一个命令中多次重复使用一些代码......你可以用一个巨大的东西替换那个简单的选择器您不想每次都重新输入吗?

提前致谢

【问题讨论】:

  • 为什么最大99?你可以使用\,{2,}
  • 啊,谢谢 Gabi Purcaru :),我也在努力解决这个问题 :)

标签: regex format rule textselection


【解决方案1】:

解决方案还取决于您的数据质量。如果您可以保证不会出现例如“[,,,,}”,则不需要复杂的正则表达式。

[\[\{](,{2,})[\]\}]

那时会做的。另外,您只想选择逗号,所以我在这个正则表达式中只使用了括号。

【讨论】:

    【解决方案2】:

    这是一个棘手的问题。它应该可以工作,但可能取决于您使用的正则表达式引擎。不过看起来很可怕。

    (?=[{[])(\{)?(\[)?(,{2,})(?(1)\})(?(2)\])
    

    解释:

    (?=[{[])    #Look ahead to check that the next charactor is in your set of opening brackets
                 # but do not capture the charactor yet.
    
    (\{)?        #Try to capture a {
    
    (\[)?        #Try to capture a [
    
    (,{2,})      #The commas (or whatever else you like).
                 #Note that these are only writen once.
    
    (?(1)\})     #If you previously captured the { then also capture a }
    
    (?(2)\])     #If you previously captured the [ then also capture a ]
    

    【讨论】:

    • 我已经对此进行了测试,并且正在使用 .NET 框架,但似乎 JavaScript 不支持它。
    • 感谢 Buh Buh,它看起来确实有点复杂 :) 可惜它不能与 javascript 一起使用,因为它是我正在使用的环境。但感谢您的帮助。
    【解决方案3】:

    您可以使用一个变量并将其与您的正则表达式连接多次。

    【讨论】:

    • 你的意思是在正则表达式之外声明它?例如像javascript,然后将其添加到new RegExp(variable...);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多