用于指定空字符串的正则表达式 [英] Regex for specifying an empty string

查看:1058
本文介绍了用于指定空字符串的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的验证器需要指定正则表达式。在验证空字符串的情况下,我不知道如何生成这样的正则表达式。我可以用什么正则表达式匹配空字符串?

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 and Matcher.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆