1

Java で解析する必要がある (Wiki マークアップからの) このような文字列がある場合:

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

[[ ]] 内のテキストを抽出するために正規表現を使用したいのですが、括弧内にある場合はそうではありません。たとえば、上記の例では、次のように返されます。

notInParen

しかし、無視してください:

inParen and this

...それらは括弧内にあるためです。かっことかっこを別々に問題なく見つけることができます。

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

...しかし、 [[ ]] を見つける方法、括弧を探して無視する方法がわかりません。ありがとう!

4

3 に答える 3

4

それは一度に行う必要がありますか?できるよ:

  • 文字列を解析し、括弧に含まれるすべての部分文字列を削除します。
  • 結果を再度解析し、必要なすべてのウィキペディア リンクを と で取得し[[ます]]

これにより、問題が解決され、問題が解決しやすくなります。

ステップ 1 の後、以下が得られますthis link one is [[ notInParen ]]

ステップ 2 の後、次のようになりますnotInParen

于 2012-06-05T19:45:12.413 に答える
1

これは素晴らしい正規表現です

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

希望する試合はグループ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は空になることに注意してください。

于 2012-06-05T19:57:51.630 に答える
0

このようにすることもできます

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 ]]
于 2012-06-05T20:07:25.837 に答える