gpt4 book ai didi

regex - 成对括号的正则表达式

转载 作者:行者123 更新时间:2023-12-02 01:17:22 24 4
gpt4 key购买 nike

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

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

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

[[text[[text text TEXT text]]

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

[[text [text] text TEXT text]]

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

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

最佳答案

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

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

它将匹配 [[match [this] text]]

[[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]]]因为正则表达式不能计数。

关于regex - 成对括号的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9580319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com