Trying to extract strings that are wrapped in double brackets. For example [[this is one token]] that should be matched. To make things more elegant, there should be an escape sequence so that double bracketed items like \[[this escaped token\]] don't get matched.
The pattern [^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})
with "group 1" to extract the token is close, but there are situations where it doesn't work. The problem seems to be that the first "not" statement is being evaluated as "anything except a backslash". The problem is, "anything" is not including "nothing". So, what would make this pattern match "nothing or any character other than a backslash"?
Here is a unit test to show the desired behavior:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import junit.framework.TestCase;
public class RegexSpike extends TestCase {
private String regex;
private Pattern pattern;
private Matcher matcher;
@Override
protected void setUp() throws Exception {
super.setUp();
regex = "[^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})";
pattern = Pattern.compile(regex);
}
private String runRegex(String testString) {
matcher = pattern.matcher(testString);
return matcher.find() ? matcher.group(1) : "NOT FOUND";
}
public void testBeginsWithTag_Passes() {
assertEquals("[[should work]]", runRegex("[[should work]]"));
}
public void testBeginsWithSpaces_Passes() {
assertEquals("[[should work]]", runRegex(" [[should work]]"));
}
public void testBeginsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("anything here[[should
work]]"));
}
public void testEndsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("[[should
work]]with anything here"));
}
public void testBeginsAndEndsWithChars_Passes() {
assertEquals("[[should work]]", runRegex("anything here[[should
work]]and anything here"));
}
public void testFirstBracketsEscaped_Fails() {
assertEquals("NOT FOUND", runRegex("\\[[should NOT work]]"));
}
public void testSingleBrackets_Fails() {
assertEquals("NOT FOUND", runRegex("[should NOT work]"));
}
public void testSecondBracketsEscaped_Fails() {
assertEquals("NOT FOUND", runRegex("[[should NOT work\\]]"));
}
}