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 ;
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 ^^
+ 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 ^^
0
visph , Yes I know that just forgot to implement it, but is there a shorter way
0
Akshay Harshora , elaborate please
0
visph , Okay and Thanks for the help