Home > Blockchain >  Regex for accepting only Paranthesis in input
Regex for accepting only Paranthesis in input

Time:10-05

i want to write a Regex expression to accept only "(", ")","{","}","[","]" these values in input, anything other then this should be invalid input. Here's my code:

    {
        public static void main(String[] args) {
        String regex = "^.*[\\(\\)\\{\\}\\[\\]].*$";
          //Reading input from user
          Scanner sc = new Scanner(System.in);
          System.out.println("Enter data: ");
          String input = sc.nextLine();
          //Instantiating the Pattern class
          Pattern pattern = Pattern.compile(regex);
          //Instantiating the Matcher class
          Matcher matcher = pattern.matcher(input);
          //verifying whether a match occurred
          if(matcher.find()) {
             System.out.println("Input accepted");
          }else {
             System.out.println("Not accepted");
            }
        }
    }```

I also tried String regex = "^.[\\(\\)\\{\\}\\[\\]]*.$", it doesn't work.

{(}){(}) - Valid input
P{())}}() - invalid input
12{}() - invalid input
.;/{{}) - invalid input
{}}} - valid input

CodePudding user response:

Edit

Java doesn't use /s to represent regex. So the fix would be:

String regex = "^[\{\}\(\)\[\]]*$";
// The rest of the code

Original Answer

Try using this /^[\{\}\(\)\[\]]*$/

CodePudding user response:

Since all of them (, ),{,},[,] are special character in regex,you need to escape them by using \ in regex expresssion, in order to archinve your golal, we can use ^[\(\)\[\]\{\}] $ to do it

Regex Demo

In java,the expression is as below:

String regex ="^[\\(\\)\\[\\]\\{\\}] $";
  • Related