Hi,
so I want to check if all characters in text are \w or \s if yes then true if even one character isn't \w or \s then false. How can it be done?:)
Language: javascript
Hi,
so I want to check if all characters in text are \w or \s if yes then true if even one character isn't \w or \s then false. How can it be done?:)
Language: javascript
.*[^\w\s].*
should do it but you don't say which language you're using
(if that regexp matches then the string fails your check)
^(\w|\s)*$
Use +
instead of *
if you don't want to accept the empty string.
You want to match against this regex:
^[\w\s]*$
The [...]
construct is called a "character class". The ^
and $
are the beginning and end of string anchors. The *
metacharacter means "zero or more repetition of". If you want at least one character (i.e. no empty string), then use +
.
Here's one in Java:
String[] tests = {
"",
" ",
"blah blah blah",
"123_456",
"#@*&#!",
};
for (String test : tests) {
System.out.println("[" + test + "] " + test.matches("^[\\w\\s]*$"));
}
This prints:
[] true
[ ] true
[blah blah blah] true
[123_456] true
[#@*&#!] false
Note that the backslashes in the regex is (seemingly) doubled: this is because \
is an escape character in Java string literals. This doubling is applicable to a few other languages as well.
Also, in Java, String.matches
is done against the entire string, so the ^
and $
anchors aren't strictly necessary in this case. When asking regex-related question, it's important to note what language you're using, due to minor variations in the different flavors.