简体   繁体   中英

How to find all special characters and print them in a given string?

I need to find all special characters and even the spaces in a sting and print it as a out put..

I have tried the following.

public class SpecialChar {

    public static void main(String[] args) {

        String s = "adad , dsd  r dsdsd,,,,..////";

        for (int i = 0; i < s.length(); i++) 
        {
            System.out.println(s.charAt(i));
        }

        System.out.println("i");


        String REGEX = "[^&%$#@!~ ,]*";
        Pattern pattern = Pattern.compile(REGEX);

        Matcher matcher = pattern.matcher(i);
        if (matcher.matches()) {
            System.out.println("matched");
        }
    }
}

A little regex will work for you :)

public static void main(String[] args) {
    String s = "adad , dsd  r dsdsd,,,,..////";
    System.out.println(s.replaceAll("[a-zA-Z]+", "")); // remove everything apart from "a-z and A-Z"

}

O/P:

 ,    ,,,,..////

I just want to point out to your problem, you're using the following regex:

[^&%$#@!~ ,]*

which means "any literal expect one of "&%$#@!~ ,".

Note that your set begins with ^ , this means that it negates the set and matches every literal that's not in that set.

You have two options: Escape the ^ , or move it to the last position.

I don't know if this is what you need but here it is:

       String s = "adad , dsd  r dsdsd,,,,..////";

    String REGEX = "[,./]";
    Pattern pattern = Pattern.compile(REGEX);
    Matcher matcher = pattern.matcher(s);

    for (int i = 0; i < s.length(); i++) {
        if (matcher.find()) {
            System.out.println(matcher.group(0));
        }
    }

If you do not want to use regex, you could try the following:

public static void main(String[] args) {

    String s = "adad , dsd  r dsdsd,,,,..////";
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!Character.isLetterOrDigit(c)) {
            System.out.print(c);
        }
    }

}

Here you use the existing API in Character class which will be used to check if a character is a letter or a digit, if not print it.

public class SpecialChar {

public static void main(String[] args) {
    String s = "adad , dsd  r dsdsd,,,,..////";

    for (int i = 0; i < s.length(); i++) {
        if (!(((int) s.charAt(i) >= 65 && (int) s.charAt(i) <= 90) || ((int) s.charAt(i) >= 97 && (int) s.charAt(i) <= 122)))
            System.out.println(s.charAt(i));
    }
}
}

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