How to check spaces and special characters are in the string excluding underscores and points


This question already has an answer here:

  • Removing whitespace from strings in Java 26 answers

I have a String in Java that I want to check for whitespace and special characters excluding underscores and periods. What would be the best way to do so?


This is how I solved this particular problem:

            String actualString = "string";
            String testString = actualString;
            testString = testString.replaceAll("_", "");
            testString = testString.replaceAll("\\.", "");
            Pattern whiteSpaceP = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);
            Matcher whiteSpaceM = whiteSpaceP.matcher(testString);
            Pattern specCharP = Pattern.compile("\\W", Pattern.CASE_INSENSITIVE);
            Matcher specCharM = specCharP.matcher(testString);
            if(whiteSpaceM.find() || specCharM.find()) {
               System.out.println("There are spaces and non-alphanumeric characters excluding . and _ in the string");

The best way to do so would be to use a Regular Expression, or Regex, or Pattern. The amount of documentation and tutorials available for regexs is so huge for all languages that I don't think it is worth saying more here. You should research the term and learn how to use them as they are an essential tool for any programmer in a wide variety of situations!