0

Is possible, in java, to make a regex for matching the end of the string but not the newlines, using the Pattern.DOTALL option and searching for a line with \n?

Examples:

1)

aaa\n==test==\naaa\nbbb\naaa

2)

bbb\naaa==toast==cccdd\nb\nc

3)

aaa\n==trick==\naaaDDDaaa\nbbb

I want to match

\naaa\nbbb\naaa

and

cccdd\nb\nc

but, in the third example, i don't want to match text ater DDD.

\naaa
4

2 に答える 2

1

はいあります。たとえば(?-m)}$、Javaソースファイルの最後にある中括弧と一致します。ポイントは、マルチラインモードを無効にすることです。これまでに示したように、またはインスタンスに適切なフラグを設定することで、無効にすることができPatternます。

更新:インスタンス化すると、マルチラインはデフォルトでオフになっていると思いますがPattern、正規表現によるEclipseの検索ではオンになっています。

于 2012-05-09T18:23:58.640 に答える
0

必要な正規表現は次のとおりです。

"(?s)==(?!.*?==)([^(?:DDD)]*)"

完全なコードは次のとおりです。

String[] sarr = {"aaa\n==test==\naaa\nbbb\naaa", "bbb\naaa==toast==cccdd\nb\nc", 
                 "aaa\n==trick==\naaaDDDaaa\nbbb"};

Pattern pt = Pattern.compile("(?s)==(?!.*?==)([^(?:DDD)]*)");

for (String s : sarr) {
    Matcher m = pt.matcher(s);
    System.out.print("For input: [" + s + "] => ");
    if (m.find())
        System.out.println("Matched: [" + m.group(1) + ']');
    else
        System.out.println("Didn't Match");
}

出力:

For input: [aaa\n==test==\naaa\nbbb\naaa] => Matched: [\naaa\nbbb\naaa]
For input: [bbb\naaa==toast==cccdd\nb\nc] => Matched: [cccdd\nb\nc]
For input: [aaa\n==trick==\naaaDDDaaa\nbbb] => Matched: [\naaa]
于 2012-05-09T20:12:09.870 に答える