0

Just a little question.

I have to quote a text inside a couple of string taking the first occurrence of one and the last occurrence of other.

Ex.

[quote]
Hi to all
[quote]
im fine
[/quote]
[/quote]

I hate to inscribe all the quoted text inside a DIV. So I have a regexp like:

String pattern = "\\[quote\\](.*?)\\[\\\quote\\\]";
body = body.replaceAll(pattern, "<div class=\"quote\">[quote]$1[/quote]</div>"); 

It works but the regexp take from first [quote] to first [/quote] leaving the second [/quote] outside the DIV. What I want obtain is:

<div class="quote">
[quote]
Hi to all
[quote]
im fine
[/quote]
[/quote]
</div>

Thanks.

4

1 回答 1

1

It sounds like, as @nhahtdh says, you simply want to remove the ? to make the * greedy.

Compare:

public static void main(String[] args) {
    String    input = "[quote]\n"
        + "Hi to all\n"  
        + "[quote]\n"
        + "im fine\n"
        + "[/quote]\n"
        + "[/quote]\n";

    System.out.println( input.replaceAll( "(?s)\\[quote\\](.*?)\\[/quote]", "<div class=\"quote\">\n[quote]$1[/quote]\n</div>" ));
    System.out.println();
    System.out.println( input.replaceAll( "(?s)\\[quote\\](.*)\\[/quote]", "<div class=\"quote\">\n[quote]$1[/quote]\n</div>" ));
  }

output:

<div class="quote">
[quote]
Hi to all
[quote]
im fine
[/quote]
</div>
[/quote]


<div class="quote">
[quote]
Hi to all
[quote]
im fine
[/quote]
[/quote]
</div>
于 2012-07-23T12:42:56.243 回答