Essaye d'extraire les chaînes qui sont enveloppées dans des doubles parenthèses. Par exemple [[ceci est un jeton]] qui devrait correspondre. Pour rendre les choses plus élégantes, il devrait y avoir une séquence d'échappement afin que les éléments entre crochets comme \ [[ce jeton d'échappement \]] ne soient pas appariés.RegEx en Java ne fonctionne pas comme prévu
Le motif [^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})
avec le "groupe 1" pour extraire le jeton est proche, mais il y a des situations où cela ne fonctionne pas. Le problème semble être que la première déclaration "non" est évaluée comme "n'importe quoi sauf une barre oblique inverse". Le problème est que "n'importe quoi" n'inclut pas "rien". Alors, qu'est-ce qui ferait correspondre ce motif à "rien ou n'importe quel caractère autre qu'un antislash"?
Voici un test unitaire pour montrer le comportement souhaité:
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\\]]"));
}
}
ne signifie rien NULL ou des espaces? – northpole