如何测试 perl 中的字符串是否只有空格
使用正则表达式测试字符串是否仅包含空白字符的好方法是什么?
Whats a good way to test to see if a string is only full of whitespace characters with regex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(我决定编辑我的帖子,将概念包含在下面与 tobyodavies 的对话中。)
在大多数情况下,您想要确定某些内容是否是空格,因为空格相对无关紧要,并且您想要跳过仅由以下内容组成的字符串空白。所以,我认为你要确定的是是否有重要的人物。
所以我倾向于使用反向测试:
$str =~ /\S/
。确定谓词“字符串包含一个S有效字符”。但是,要应用您的特定问题,可以通过测试来确定是否定的:
$str !~ /\S/
(I have decided to edit my post to include concepts in the below conversation with tobyodavies.)
In most instances, you want to determine whether or not something is whitespace, because whitespace is relatively insignificant and you want to skip over a string consisting of merely whitespace. So, I think what you want to determine is whether or not there are significant characters.
So I tend to use the reverse test:
$str =~ /\S/
. Determining the predicate "string contains one Significant character".However, to apply your particular question, this can be determined in the negative by testing:
$str !~ /\S/
您的正则表达式语句应该查找 ^\s+$。它将需要至少一个空格。
如果您想知道,“空白被定义为 [\t\n\f\r\p{Z}]”。请参阅http://userguide.icu-project.org/strings/regexp。
Your regex statement should look for ^\s+$. It will require at least one whitespace.
In case you were wondering, "white space is defined as [\t\n\f\r\p{Z}]". See http://userguide.icu-project.org/strings/regexp.