简体   繁体   English

VB.Net-正则表达式问题

[英]VB.Net - Regex Issue

I try to make a Regex pattern, that recognizes [== and ==] . 我尝试制作一个正则表达式模式,该模式可以识别[====] It doesn't matter how much text is between [== and ==] , also it should match it, if there are new lines between. [====]之间有多少文本都没有关系,如果之间有新行,也应该匹配它。 But It should always match to the next occurence that means if I have sth like this. 但是它应该始终与下一个事件匹配,这意味着如果我有这样的事情。

[== Cats and Dogs ==]  --> Match

or 要么

[== fsdfd
sdfsdf

sdfsdf ==]             --> Match

[== ddasdas [== asdsd ==]  --> Match 

from the first [== to the last ==] . 从第一个[==到最后一个==] It needs to ignore the second [== if there is no closing bracket. 如果没有右括号,则需要忽略第二个[==

How can I do this? 我怎样才能做到这一点?

There are three possible approaches, none of which will work in all cases because your requirements are mutually exclusive. 共有三种可能的方法,但由于您的要求是相互排斥的,因此在所有情况下都无法使用。

  1. The solution that matches all the cases in your question (assuming you meant ==] where you wrote =] ; I "fixed" those cases): 与问题中所有情况匹配的解决方案(假设您的意思是==]您写的位置=] ;我“修复”了这些情况):

     Dim RegexObj As New Regex("\\[==.*?==\\]", RegexOptions.Singleline) 

    This matches from the leftmost [== until the first ==] . 从最左边的[==直到第一个==]匹配。 It will not handle nested brackets correctly, as in my comment above where the result will be [== foo [== bar ==] . 它将无法正确处理嵌套的括号,就像我在上面的评论中,结果将是[== foo [== bar ==]

  2. The solution that matches all the cases, including the one in my comment, but only works if there is exactly one possible match in the entire input string: 该解决方案可匹配所有情况,包括我的评论中的情况,但仅在整个输入字符串中可能存在一个完全匹配的情况下才有效:

     Dim RegexObj As New Regex("\\[==.*==\\]", RegexOptions.Singleline) 

    This matches from the leftmost [== until the last ==] it finds. 这从找到的最左边的[==到最后一个==]匹配。

  3. The solution that handles nested cases correctly, but fails on improperly nested cases (for example, matching only [== asdsd ==] when applied to [== ddasdas [== asdsd ==] : 该手柄正确的嵌套的情况,但是该解决方案在不正确嵌套例失败(例如,只匹配[== asdsd ==]当施加到[== ddasdas [== asdsd ==]

     Dim RegexObj As New Regex( _ "\\[== # Match [==" & chr(10) & _ "(?> # Then either match (possessively):" & chr(10) & _ " (?: # the following group which matches" & chr(10) & _ " (?!\\[==|==\\]) # only if we're not before a [== or ==]" & chr(10) & _ " . # any character" & chr(10) & _ " )+ # once or more" & chr(10) & _ "| # or" & chr(10) & _ " \\[== (?<Depth>) # [== (and increase the nesting counter)" & chr(10) & _ "| # or" & chr(10) & _ " ==\\] (?<-Depth>) # ==] (and decrease the nesting counter)." & chr(10) & _ ")* # Repeat as needed." & chr(10) & _ "(?(Depth)(?!)) # Assert that the nesting counter is at zero." & chr(10) & _ "==\\] # Then match ==].", _ RegexOptions.IgnorePatternWhitespace Or RegexOptions.Singleline) 

Pick one :) 选一个 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM