简体   繁体   中英

How to check is string contains any of special characters?

I want to check is some string contains ANY special symbol from UNICODE charset or not. Previosly I harcoded it with regular expression charset, but now list of chars expanded and its not an option to hardcode it now. How to set this check?

You could loop through your string and for every character call, then

public static boolean checkingUnicode(String text){

        char[] arr = text.toCharArray();

        for(int i=0; i<arr.length; i++){
            char c = arr[i];
            if(Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN){
                return true;
            }
        }
        return false;
    }

Hope it works

There is an option using Regex.

If it matches regex [a-zA-Z0-9 ] then there is not special characters in it.

Pattern p = Pattern.compile("[a-zA-Z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean containsSpecialChar = m.find();
if(containsSpecialChar){
// Do what you need.
}

Hope this will help you.

I think it can be achieve. You need to make a possible list of special characters defined and apply condition in loop for check every character in list for containing that special character.

use the method called Regex.

                String s= e2.getText().toString();
                Pattern pattern = Pattern.compile("\\d{11}"); //CHANGE PATTERN CONDITIONS ACCORDINGLY
                Matcher matcher = pattern.matcher(s); //CHECKS THE PATTERN WITH THE INPUT STRING

                if (matcher.matches()) {
                   // YOUR METHODS 
                }
                else
                {
                    //PRINT AN ERROR TEXT
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM