开发者

how to use Matcher.replaceAll in java?

开发者 https://www.devze.com 2023-02-09 20:15 出处:网络
i have a file which contains \"(*\" and \"*)\". i want to remove everything betwe开发者_StackOverflow中文版en this two char sequences.

i have a file which contains "(*" and "*)". i want to remove everything betwe开发者_StackOverflow中文版en this two char sequences. i used the following code but it didn't do anything with my string.

    String regex = "\\(\\*.*\\*\\)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    matcher.replaceAll("");

the 'input' is:

(* This program prints out a message. *)

program is

  begin
    write ("Hello, world!");
  end;


You need to capture the return value of your matcher - it's replaceAll method returns the replaced String.

Additionally, use a regexp to match what you want to match, this time a parenthesized String. If you don't have some strange inputs, it may look like this:

String regex = "\\(\\*.*\\*\\)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("(\\*\\*)");
System.out.println(result);

This regexp in fact captures the whole region from the first comment start to the last comment end, which would usually not be what you want. To let it match non-greedy (reluctantly), use this regexp: \(\*.*?\*\) (with doubled backslashes in Java.)

0

精彩评论

暂无评论...
验证码 换一张
取 消