2

假设我有以下文本:

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 labourum。

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

(\,{2,99})

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

这会失败的地方:

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

以下将按预期工作

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

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

有什么方法可以在同一命令中声明 avariable以后可以应用吗?像:

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

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

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

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

提前致谢

4

3 回答 3

1

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

于 2011-06-21T13:05:22.773 回答
0

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

(?=[{[])(\{)?(\[)?(,{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 ]
于 2011-06-21T13:29:44.663 回答
0

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

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

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

于 2011-06-21T14:25:47.887 回答