Given a string containing some number of square brackets and other characters, I want to find all closing square brackets preceded by an opening square bracket and some number of letters.
For instance, if the string is
] [abc] [123] abc]
I want to find only the second closing bracket.
The following regex
(?<=[a-z]+)\]
will find me the second closing bracket, but also the last one:
] [abc] [123] abc]
Since I want to find only the first one, I make the obvious change to the regex…
(?<=\[[a-z]+)\]
…and I get “Look-behind group does not have an obvious maximum length near index 11.”
\[ is only a single character, so it seems like the obvious maximum length should be 1 + whatever the obvious maximum length was of the look-behind group in the first expression. What gives?
ETA: It’s not specific to the opening bracket.
(?<=a[b-z]+)\]
gives me the same error. (Well, at index 12.)
That’s the point, “whatever the obvious maximum length was of the look-behind group in the first expression”, is not obvious. A rule of fist is that you can’t use
+or*inside a look-behind. This is not only so for Java’s regex engine, but for many more PCRE-flavored engines (even Perl’s (v5.10) engine!).You can do this with look-aheads however:
(I.e. a capture group inside a look ahead (!) which can be used to get the
end(...)of the group)will print:
EDIT
And if you’re interested in replacing such
]‘s, you could do something like this:which will print: