用于指定空字符串的正则表达式 [英] Regex for specifying an empty string
问题描述
我使用的验证器需要指定正则表达式。在验证空字符串的情况下,我不知道如何生成这样的正则表达式。我可以用什么正则表达式匹配空字符串?
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?
推荐答案
正则表达式 ^ $
仅匹配空字符串(即长度为0的字符串)。这里 ^
和 $
分别是字符串锚点的开头和结尾。
The regex ^$
matches only empty strings (i.e. strings of length 0). Here ^
and $
are the beginning and end of the string anchors, respectively.
如果需要检查字符串是否只包含空格,可以使用 ^ \s * $
。请注意, \s
是空白字符类的简写。
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.
最后,在Java中,匹配
尝试匹配整个字符串,因此您可以在选择时省略锚点。
Finally, in Java, matches
attempts to match against the entire string, so you can omit the anchors should you choose to.
- regular-expressions.info/Character classes and Anchors
String.matches
,Pattern.matches
andMatcher.matches
您还可以使用 String.isEmpty()
检查字符串的长度是否为0.如果要查看字符串是否只包含空格字符,则可以 trim()
首先和然后检查它是否是 isEmpty()
。
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()
.
这篇关于用于指定空字符串的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!