0

I am looking for a regular expression in Java where I can remove the beginning and end of the angular braces if both are present in the string. e.g. 1

str = "abc <someting> def < 0"
output: "abc someting def < 0"

if there is either open or close then that brace should remain as it is.

e.g. 2

str = "abc <some <thing>> def < 0"
output : "abc some thing def < 0"

I followed other stackoverflow QA but nothing helped me.

Below are the one I tried

"\\<[^\\>]*?\\)"
"\\<|\\>"

Thanks in advance!!!

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • 7
    If you've got `some ` as input, what should the output be: `some – Nick Reed Jan 02 '20 at 20:29
  • 10
    Java regex doesn't support recursive patterns, better you use a parser. – anubhava Jan 02 '20 at 20:29
  • @NickReed, OP seems to talk about well-balanced brackets, but not sure (upvoted comment though). – Amessihel Jan 02 '20 at 21:06
  • I personally like the `appendReplacement() and appendTail()` answer here https://stackoverflow.com/questions/375420/java-equivalent-to-phps-preg-replace-callback but any call back way would work. Each match, remove all `<` or `>` from group 0, then append (or replace) to the new string. Regex : `"(?s)(?=<)(?:(?=.*?<(?!.*?\\1)(.*>(?!.*\\2).*))(?=.*?>(?!.*?\\2)(.*)).)+?.*?(?=\\1)[^<]*(?=\\2$)"` https://regex101.com/r/mbdquf/1 Note that each match is guaranteed to have balanced angle brackets. –  Jan 02 '20 at 21:25

1 Answers1

1

You could perform a looping regexp replace until no changes are done. I assumed you were talking about bracket-free text surrounded by brackets. In that case, the regex is <([^>]*)>, which captures the inner text in the first group (named $1).

In the sample below, a while loop line checks if the str value is different than the result of str.replaceAll(), which is assigned to str after1 the check. If they are equals, the loop ends, i.e. nothing where replaced so there are no brackets to remove.

public class Test {
    public static void main(String args[]) {
        String str = "abc <some <thing>> def < 0";
        while (!str.equals(str = str.replaceAll("<([^>]*)>", "$1")));
        System.out.println(str);
    }
}

Output:

~$ javac Test.java
~$ java Test
abc some thing def < 0

1 target reference of str.equals() is made before the argument evaluation, so before the assignement.

Amessihel
  • 5,891
  • 3
  • 16
  • 40
  • [Comparing strings with `==` or `!=` is not safe.](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – VGR Jan 02 '20 at 23:55
  • @VGR, you should remove your comment, since the answer was edited meanwhile. – Amessihel Jan 28 '20 at 18:13