-2

I am struggling and have looked up many resources. I appreciate your time and patience. I would like to extract everything in a string BUT what is between two brackets, including the brackets themselves.

Duck, Donald [CTO Enterprise] Mouse, Micky [HR Employee Engagement]

I would like to just have:

Duck, Donald Mouse, Micky

So far I have been badly manipulating

[A-Za-z, ][^\[(.*?)\]]

But to no avail.

Thank You!!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Drewm
  • 1
  • 1

1 Answers1

0

You may try:

\s*\[.*?[^\[]*\]

Explanation of the above regex:

\s* - matches any whitespace character (equal to [\r\n\t\f\v ]) zero or more times.

[.*?[^\[]*\] - Matches the square brackets literally and matches everything inside square brackets lazily. It will even replace the nested brackets if that is your requirement too.

pictorial representation

You can find the demo of the regex in here.

Implementation in java:

public class Main
{
    public static void main(String[] args) {
        String str = "Duck, Donald [CTO Enterprise] Mouse, Micky [HR Employee Engagement]";
        System.out.println(str.replaceAll("\\s*\\[.*?[^\\[]*\\]", ""));
    }
}
// outputs: Duck, Donald Mouse, Micky

You can find the sample run of the above code in here.

Community
  • 1
  • 1