Search code examples
javaregexregex-greedy

How do I write a regex that matches a certain character within brackets?


So I have a string that's like this,

(name|address)
([name|address])
[name|address]

So I want to check for '|' character and ignore if it's in the brackets like I have shown in the example.

I have added this regex but it's not capturing all scenarios that I have described.

\\|(?![^(]*\\))

Edit:

If I have string like this,

|Hello all, | morning [name|address] |

Then I am breaking the string by | character. But I don't want to consider | character which are inside the brackets while breaking the string.


Solution

  • You can use

    import java.util.*;
    import java.util.regex.*;
    
    class Test
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            String s = "|Hello all, | morning [name|address] |";
            Pattern pattern = Pattern.compile("(?:\\([^()]*\\)|\\[[^\\]\\[]*]|[^|])+");
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()){
                System.out.println(matcher.group().trim()); 
            } 
        }
    }
    

    See the regex demo and the Java demo.

    Details:

    • (?: - start of a non-capturing group:
      • \([^()]*\)| - (, zero or more chars other than ( and ), and then a ) char, or
      • \[[^\]\[]*]| - [, zero or more chars other than a [ or ] char, and then a ] char, or
      • [^|] - any single char other than a pipe char
    • )+ - end of the group, repeat one or more times.

    Note that in Android, Java, ICU regex flavors, both [ and ] must be escaped inside character classes.