Skip to main content
 首页 » 编程设计

c#之方括号中的正则表达式前面或后面没有

2024年02月13日31lexus

我正在尝试在 C# 中创建一个正则表达式模式以在字符串中查找任何前面或后面没有“.”的 [anything]...这是我到目前为止的模式,这让我想到实际问题:它只适用于不在第一行的文本??

图案:

([^\.]\[[^\[]*][^\.]) 

考虑以下“文本”值:

[F] (never matches even if it should) 
 
[F].[1234] (not a match, correct) 
 
[P] (is a match) 

如果有人能帮我解决这个问题,我将不胜感激,因为我这辈子都无法弄清楚为什么不考虑第一行。

谢谢!

请您参考如下方法:

您编写的正则表达式验证第一个 [ 前面必须有一个不是 . 的字符。第一个 [ 前面没有任何字符,因此失败。

对于否定断言,您可以说“如果没有 . 则匹配”。

((?<!\.)\[[^\[]*](?!\.)) 
 
 
NODE                     EXPLANATION 
-------------------------------------------------------------------------------- 
  (                        group and capture to \1: 
-------------------------------------------------------------------------------- 
    (?<!                     look behind to see if there is not: 
-------------------------------------------------------------------------------- 
      \.                       '.' 
-------------------------------------------------------------------------------- 
    )                        end of look-behind 
-------------------------------------------------------------------------------- 
    \[                       '[' 
-------------------------------------------------------------------------------- 
    [^\[]*                   any character except: '\[' (0 or more 
                             times (matching the most amount 
                             possible)) 
-------------------------------------------------------------------------------- 
    ]                        ']' 
-------------------------------------------------------------------------------- 
    (?!                      look ahead to see if there is not: 
-------------------------------------------------------------------------------- 
      \.                       '.' 
-------------------------------------------------------------------------------- 
    )                        end of look-ahead 
-------------------------------------------------------------------------------- 
  )                        end of \1