0

How to check using regular expression that atleast two different character from [ . ] is present in my string ?

Suppose I want to check that my string contains atleast two different character from following : [@,#,&,+,*,?] . Which regex is going to help me here ? I tried this : if(s.matches(".*[@#&+*?].*[@#&+*?].*") ) return true ; , but I knew it will fail for string like "abc@@" as it contains only single special character from my list repeated twice. I can solve this but the regex will be really long and inefficient, is there a simple way other than this : if(s.matches(".*@+.*[#&+*?]+.*") || s.matches(".*#+.*[@&+*?]+.*") || s.matches(".*&+.*[#@+*?]+.*") || s.matches(".*\\++.*[#&@*?]+.*") || s.matches(".*\\*+.*[#&+@?]+.*") || s.matches(".*\\?+.*[#&+*@]+.*") ) return true ;

20th May 2021, 6:52 AM
Mr.Curious
Mr.Curious - avatar
5 Réponses
+ 1
you can test against only one regex by doing the OR operations inside it: if (s.matches(".*(@.*[#&+*?]|#.*[@&+*?]|&.*[@#+*?]|\\+.*[@#&*?]|\\*.*[@#&+?]|\\?.*[@#&+*]).*")) return true; parenthesis are here to spare some char and increase efficiency... also, suggestion of Akshay Harshora could improve efficiency if you're doing a lot of check with the same pattern ^^
20th May 2021, 1:08 PM
visph
visph - avatar
+ 1
as far as I know, there's no shorter way... but it would increase efficiency compared to your code (and it's shorter), where there are many regex to test ^^
20th May 2021, 1:47 PM
visph
visph - avatar
0
visph , Yes I know that just forgot to implement it, but is there a shorter way
20th May 2021, 1:44 PM
Mr.Curious
Mr.Curious - avatar
0
Akshay Harshora , elaborate please
20th May 2021, 1:45 PM
Mr.Curious
Mr.Curious - avatar
0
visph , Okay and Thanks for the help
20th May 2021, 1:52 PM
Mr.Curious
Mr.Curious - avatar