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
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
In java,the expression is as below:
String regex ="^[\\(\\)\\[\\]\\{\\}]+$";