如何测试 perl 中的字符串是否只有空格

发布于 2024-11-09 04:15:12 字数 36 浏览 0 评论 0原文

使用正则表达式测试字符串是否仅包含空白字符的好方法是什么?

Whats a good way to test to see if a string is only full of whitespace characters with regex?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

简单 2024-11-16 04:15:12
if($string=~/^\s*$/){
    #is 100% whitespace (remember 100% of the empty string is also whitespace)
    #use /^\s+$/ if you want to exclude the empty string
}
if($string=~/^\s*$/){
    #is 100% whitespace (remember 100% of the empty string is also whitespace)
    #use /^\s+$/ if you want to exclude the empty string
}
二智少女猫性小仙女 2024-11-16 04:15:12

(我决定编辑我的帖子,将概念包含在下面与 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/

顾挽 2024-11-16 04:15:12

您的正则表达式语句应该查找 ^\s+$。它将需要至少一个空格。

如果您想知道,“空白被定义为 [\t\n\f\r\p{Z}]”。请参阅http://userguide.icu-project.org/strings/regexp

\t  Match a HORIZONTAL TABULATION, \u0009.
\n  Match a LINE FEED, \u000A.
\f  Match a FORM FEED, \u000C.
\r  Match a CARRIAGE RETURN, \u000D.
\p{UNICODE PROPERTY NAME}   Match any character with the specified Unicode Property.

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.

\t  Match a HORIZONTAL TABULATION, \u0009.
\n  Match a LINE FEED, \u000A.
\f  Match a FORM FEED, \u000C.
\r  Match a CARRIAGE RETURN, \u000D.
\p{UNICODE PROPERTY NAME}   Match any character with the specified Unicode Property.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文