Home > Software design >  RegEx to filter to full whitespace and special characters
RegEx to filter to full whitespace and special characters

Time:01-18

I need a RegEx to match certain special characters and if the string has only white space without any characters. I'm able to successfully match special characters but unable to match if it has full white space.

This is my RegEx to find certain characters. [^<>/\\\\:*?\"|]

but I need above RegEx to match if the string has only whitespaces ex." " it should not match even if the string has one valid character like " d"

any help is highly appreciated

CodePudding user response:

You can use this regex to match strings that are only whitespace and special characters:

[^\S\r\n]*

CodePudding user response:

in case you might just need a REGEX match in JAVA for white spaces:

Pattern whitespace = Pattern.compile("^\\s $");

so

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class regex {

public static void main(String[] args) {

    System.out.println(useRegex("This is a Test ")); // this would print false
    System.out.println(useRegex("  ")); // this would print true

}
 public static boolean useRegex(final String input) {
        // Compile regular expression
        final Pattern pattern = Pattern.compile("^\\s $", Pattern.CASE_INSENSITIVE);
        // Match regex against input
        final Matcher matcher = pattern.matcher(input);
        // Use results...
        return matcher.matches();
    }
}

CodePudding user response:

Only modify your regex to be one or more of special characters or one or more whitespace character:

^[\^<>\/\\:*?\"|] |\s $

You can test it here: https://regex101.com/r/wdCozn/1

UPDATE for JAVA we need to escape double quote too.

CodePudding user response:

To match a string with at least 1 whitespace char excluding newlines in JavaScript, you can use a negated character class:

^[^\S\r\n] $

See a regex101 demo.

In Java, you can match 1 or more times a horizontal whitspace chars:

^\\h $

See a regex101 demo.

Note that if empty strings are also allowed, then the quantifier can be * to repeat 0 or more times.

  • Related