試圖提取用雙括號括起來的字符串。例如[[這是一個令牌]]應該匹配。爲了使事情更優雅,應該有一個轉義序列,這樣像\ [[這個轉義符\]]的雙括號內容就不會匹配。Java中的RegEx無法正常工作
用「組1」提取標記的模式[^\\\\]([\\[]{2}.+[^\\\\][\\]]{2})
接近,但有些情況下它不起作用。問題似乎是,第一個「不」的語句被評估爲「除反斜線外的任何內容」。問題是,「任何事物」都不包括「無」。那麼,什麼使這種模式匹配「沒有任何或任何字符比反斜槓」?
這裏是一個單元測試來展示所需的行爲:
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\\]]"));
}
}
什麼也不做的意思是NULL或空白? – northpole 2009-06-25 16:59:20