-2
String abc=folderDocBean.getService().replaceAll("\\s+", "_");

abc = hello world (English) or hello world ((((English

expected output:- hello_world_English

In the above line it removes white spaces and ads _ in the place of whitespace..

I want to remove the braces if matching braces () exists then all braces the braces need to remove.

I have tried with abc.replaceAll("\\p{P}",""); is removing the braces but not ading any underscore to my string

abc = abc.replaceAll("\\s+", "_");
        abc = abc.replaceAll("[\\(\\)\\[\\]\\{\\}]",""); ==> it is satisfying my reqirement and how can I write the same in a single statement
user9130953
  • 449
  • 2
  • 13

1 Answers1

1

You can write the replacement using a single expression [()\\[\\]{}|]|\\s+, but that will require using a StringBuffer. Here is how you can do it:

public static void main(String[] args) {
    String abc = "hello world ((((English)) {test}";
    Pattern pat = Pattern.compile("[()\\[\\]{}|]|\\s+");
    Matcher m = pat.matcher(abc);
    StringBuffer bufStr = new StringBuffer();
    while(m.find()) {
        m.appendReplacement(bufStr, m.group().contains(" ") ? "_" : "");
    }
    m.appendTail(bufStr);
    System.out.println(bufStr);
}

So basically you have a combined regular expression which intercepts all brackets or multiple spaces and then you loop through all matches and whenever a match is found you analyse the match with m.group().contains(" "). According to whether the match contains a space or not you append either "_" or an empty string.

If you run the code above you will get this output:

hello_world_English_test
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76