-1

Would someone kindly demonstrate what the regular expession would be for matching the square brackets?

I'm currently using java.util.regex.

For example, let's say we have the following line:

public static void main (String[] args) {

I need to match only the OPEN square bracket [ and next, the close square bracket ].

I'm not saying I need to match the text between the square brackets.

I have tried with

[\\]]

and

\\]

Unfortunately, it matches the text as well and I need to match only [ or ].

The weird thing is, when I try to match the { with [\\}], it works!

Thoughts?

ervidio
  • 571
  • 5
  • 12
  • 1
    Did you try `[\[\]]`? – Abhilash Gopal Oct 25 '17 at 05:57
  • I'm seeing confusion here about basic regex concepts. Please edit your question and show us exactly what you are trying to match. – Tim Biegeleisen Oct 25 '17 at 05:59
  • 4
    Please post the code you've tried. Some characters need to be escaped with backslash in a regex, and then the backslash needs to be escaped with another backslash in string literals. It's hard to tell whether you're getting it right. – ajb Oct 25 '17 at 06:10
  • https://stackoverflow.com/questions/21282947/regular-expression-to-match-string-within-a-square-bracket – Hoque MD Zahidul Oct 25 '17 at 06:34

1 Answers1

2

You can do it using:

    String text = "[This is the text]";

    String patternString = "\\[.*.\\]";

    Pattern pattern = Pattern.compile(patternString);

    Matcher matcher = pattern.matcher(text);

    System.out.println("Matcher? " + matcher.matches());

This return true if the text has a [ and ] and false if it doesn't

Hope this can help you. Thanks.

ervidio
  • 571
  • 5
  • 12