成对括号的正则表达式 [英] Regular Expression for paired brackets

查看:94
本文介绍了成对括号的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入行是这样的(只是其中的一部分):

The Input Line goes like this (just a part of it):

[[Text Text Text]][[text text text]]asdasdasdasda[[asdasdasdasd]]

我想要的是列出所有匹配项,其中文本包含在一对 [[]] 中.我确实尝试了几种模式,但是当未关闭的 [[]] 位于输入行内时,所有模式都失败了.例如:

What I want is to list all matches wherein text enclosed in a pair of [[ and ]]. I did try several patterns, but all fails when a unclosed [[ or ]] is within the input line. For example:

[[text[[text text TEXT text]]

此外,如果输入行中存在单个括号怎么办,例如:

Also, what if a single bracket exist within the input line, like:

[[text [text] text TEXT text]]

我使用的正则表达式模式是:

The regex pattern I used was:

\[\[[^\[\[]*\]\]

推荐答案

\[\[(?:(?!\[\[|\]\]).)*\]\]

匹配 [[]],其中 可能不包含双括号,但包含其他所有内容.您可能需要设置正则表达式引擎的 DOTALL 选项以允许点匹配换行符.

matches [[<anything>]], where <anything> may not contain double brackets but everything else. You might need to set the DOTALL option of your regex engine to allow the dot to match newlines.

它将匹配

[[don't match this [[match [this] text]] don't match this]]

说明:

\[\[     # Match [[
(?:      # Match...
 (?!     #  (unless we're right at the start of
  \[\[   #   [[
 |       #  or
  \]\]   #   ]]
 )       #  )
 .       # ...any character
)*       # Repeat any number of times
\]\]     # Match ]]

警告:它将匹配文本[[match[this]]]中的[[match [this]],因为正则表达式无法计数.

Caveat: It will match [[match [this]] in the text [[match[this]]] because regexes can't count.

这篇关于成对括号的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆