簡體   English   中英

正則表達式刪除由匹配的雙括號分隔的子字符串

[英]regular expression to remove substrings delimited by matching double braces

我有一個像這樣的字符串:

adfsdf dsf  {{sadfsdfadf {{Infobox}} musical}} jljlk }}

我要消除所有{{..}}子字符串。 我試過了

\{\{.*\}\}

它消除了{{sadfsdfadf{{Infobox}} musical}} jljlk }}但我想消除{{sadfsdfadf {{Infobox}} musical}} ,檢查}}靠近子字符串的開頭。

我怎樣才能做到這一點?

使用惰性量詞:

\{\{.*?\}\}

這是一個相當健壯的表達式\\{\\{[a-zA-Z\\s]*\\}\\} ,它將起作用。

在一般情況下,使用正則表達式是不可能的。 您不能將正則表達式與平衡括號或類似的東西匹配-您需要上下文無關的語法。

也就是說,Perl具有一些遞歸正則表達式的功能; 這些將使您能夠做自己想做的事。 我不知道Ruby是否有能力做同樣的事情。

這是一個使用最新的1.9.x Ruby版本的快速示例。 如果運行1.8.x版本,則需要oniguruma gem。 這沒有考慮轉義的\\{\\{但確實處理了單個{} ,我認為您將要忽略它。

#!/usr/bin/evn ruby
# Old 1.8.x versions of Ruby you'll need the gem.
# require 'oniguruma'
require 'pp'

squiggly = %r/
  (
    (?<squiggly>         # squiggly named group
      \{\{               # start {{
        (?:              # non matching group
          [^{}]          # anything not { or }
          | \{[^{]       # any { not followed by {
          | \}[^}]       # any } not followed by }
          | \g<squiggly> # nested squiggly
        )*               # zero or more times
      \}\}               # end }}
    )                    # end of squiggly
  )/x

string = 'adfsdf dsf  {{sadfsdfadf {{Infobox}} musical}} jljlk }}'
pp squiggly.match(string)[:squiggly] #=> {{sadfsdfadf {{Infobox}} musical}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM