如何使用正则表达式检查一行是否为空 [英] How to check if a line is blank using regex
问题描述
我正在尝试制作简单的正则表达式来检查一行是否为空.
I am trying to make simple regex that will check if a line is blank or not.
案例;
" some" // not blank
" " //blank
"" // blank
推荐答案
你想要的模式在多行模式下是这样的:
The pattern you want is something like this in multiline mode:
^\s*$
说明:
^
是字符串锚点的开头.$
是字符串锚点的结尾.\s
是空白字符类.*
是零次或多次重复.
^
is the beginning of string anchor.$
is the end of string anchor.\s
is the whitespace character class.*
is zero-or-more repetition of.
在多行模式下,^
和 $
也匹配行的开头和结尾.
In multiline mode, ^
and $
also match the beginning and end of the line.
您还可以通过 trim()
-ing 检查给定字符串 line
是否为空白"(即仅包含空格),然后检查结果字符串isEmpty()
.
You can also check if a given string line
is "blank" (i.e. containing only whitespaces) by trim()
-ing it, then checking if the resulting string isEmpty()
.
在 Java 中,这将是这样的:
In Java, this would be something like this:
if (line.trim().isEmpty()) {
// line is "blank"
}
regex 解决方案也可以在没有锚的情况下简化(因为 matches
在 Java 中是如何定义的)如下:
The regex solution can also be simplified without anchors (because of how matches
is defined in Java) as follows:
if (line.matches("\\s*")) {
// line is "blank"
}
API 参考
StringString.trim()
- 返回字符串的副本,省略前导和尾随空格.
- 当且仅当
length()
为0
时返回true
. - Returns
true
if, and only if,length()
is0
. - 判断这个(整个)字符串是否与给定的正则表达式匹配.
- Tells whether or not this (entire) string matches the given regular expression.
这篇关于如何使用正则表达式检查一行是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!