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.
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 ==]
.
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.
The solution that handles nested cases correctly, but fails on improperly nested cases (for example, matching only [== asdsd ==]
when applied to [== 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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.