I use a validator that requires a regex to be specified. In the case of validating against an empty string, I don't know how to generate such a regex. What regex can I use to match the empty string?
I don't know about Java specifically, but ^$
usually works (^
matches only at the start of the string, $
only at the end).
The regex ^$
matches only empty strings (i.e. strings of length 0). Here ^
and $
are the beginning and end of the string anchors, respectively.
If you need to check if a string contains only whitespaces, you can use ^\s*$
. Note that \s
is the shorthand for the whitespace character class.
Finally, in Java, matches
attempts to match against the entire string, so you can omit the anchors should you choose to.
String.matches
, Pattern.matches
and Matcher.matches
You can also use String.isEmpty()
to check if a string has length 0. If you want to see if a string contains only whitespace characters, then you can trim()
it first and then check if it's isEmpty()
.
If you have to use regexp in Java for checking empty string you can simply use
testString.matches("")
please see examples:
String testString = "";
System.out.println(testString.matches(""));
or for checking if only white-spaces:
String testString = " ";
testString.trim().matches("");
but anyway using
testString.isEmpty();
testString.trim().isEmpty();
should be better from performance perspective.
public static void main(String[] args) {
String testString = "";
long startTime = System.currentTimeMillis();
for (int i =1; i <100000000; i++) {
// 50% of testStrings are empty.
if ((int)Math.round( Math.random()) == 0) {
testString = "";
} else {
testString = "abcd";
}
if (!testString.isEmpty()){
testString.matches("");
}
}
long endTime = System.currentTimeMillis();
System.out.println("Total testString.empty() execution time: " + (endTime-startTime) + "ms");
startTime = System.currentTimeMillis();
for (int i =1; i <100000000; i++) {
// 50% of testStrings are empty.
if ((int)Math.round( Math.random()) == 0) {
testString = "";
} else {
testString = "abcd";
}
testString.matches("");
}
endTime = System.currentTimeMillis();
System.out.println("Total testString.matches execution time: " + (endTime-startTime) + "ms");
}
Output:
C:\Java\jdk1.8.0_221\bin\java.exe
Total testString.empty() execution time: 11023ms
Total testString.matches execution time: 17831ms
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With