簡體   English   中英

在方括號中而不是括號中查找文本

[英]Find text in square brackets but not in parentheses

如果我有一個這樣的字符串(來自Wiki標記),則需要使用Java進行解析:

this link (is [[ inParen ]] and) (this) one is [[ notInParen ]]

我想使用正則表達式來提取[[]]內的文本,但是如果它們在括號內,則不會。 例如,在上面的示例中,它應返回:

notInParen

但請忽略:

inParen and this

...因為它們在括號內。 我可以分別找到括號和括號沒問題:

.*\(.*?\).* and .*?\[\[(.*?\]\].*

...但是無法弄清楚如何找到[[]],四處尋找括號並忽略。 謝謝!

是否需要一口氣完成? 你可以做:

  • 解析該字符串,並刪除括號中包含的所有子字符串。
  • 再次解析結果,並使用[[]]獲取所有所需的Wikipedia鏈接。

這解決了問題並使問題更容易解決。

在步驟1之后,您將擁有: this link one is [[ notInParen ]]

步驟2之后,您將擁有: notInParen

這是一個很好的正則表達式

\(.*?\)|\[\[(.*?)]]

您想要的比賽將在第1組中

僅供參考,為使其性能更好,您可以通過將否定的匹配項替換為否定的字符類來最大程度地減少回溯。

在Java中,這變成

String ResultString = null;
try {
    Pattern regex = Pattern.compile("\\(.*?\\)|\\[\\[(.*?)\\]\\]", Pattern.DOTALL | Pattern.MULTILINE);
    Matcher regexMatcher = regex.matcher(subjectString);
    if (regexMatcher.find()) {
        ResultString = regexMatcher.group(1);
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

請注意,對於交替的第一部分確實匹配的情況,組1將為空。

你也可以這樣

String data = "this link (is [[ inParen ]] and) (this) one is [[ notInParen ]]" +
        " this link (is [[ inParen ]] and) (this) one is [[ notInParen ]]";

boolean insideParentheses = false;
int start = 0, end = 0;
for (int i = 0; i < data.length() - 1; i++) {
    if (data.charAt(i) == '(')
        insideParentheses = true;
    if (data.charAt(i) == ')')
        insideParentheses = false;
    // -> [[ and ]] inside Parentheses are not important
    if (!insideParentheses && 
            data.charAt(i) == '[' && data.charAt(i + 1) == '[') {
        start = i;
    }
    if (!insideParentheses && 
            data.charAt(i) == ']' && data.charAt(i + 1) == ']') {
        end = i;
        System.out.println(data.substring(start, end + 2));
    }
}

輸出

[[ notInParen ]]
[[ notInParen ]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM