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?
-
4I dont see why you need a regex the check this.InsertNickHere– InsertNickHere2010-07-02 09:16:41 +00:00Commented Jul 2, 2010 at 9:16
-
2prabha commented below that a validator required it to be a regex - this should have been part of the question from the start, not a comment!Peter Boughton– Peter Boughton2010-07-02 10:35:25 +00:00Commented Jul 2, 2010 at 10:35
-
Edited the question to mention the regex requirement.Paul Bellora– Paul Bellora2013-04-30 03:17:45 +00:00Commented Apr 30, 2013 at 3:17
4 Answers
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.
References
API references
Non-regex solution
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().
1 Comment
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