正则表达式非空且非空格
我正在尝试创建一个正则表达式,如果字符串模式包含空格或为空,它将返回 false。到目前为止,我
[^\s]
认为这将确保字符串不包含空格,但我不确定如何检查以确保它不为空。任何帮助将不胜感激。
I am trying to create a regex that will return false if the String pattern contains whitespace or is empty. So far I have this
[^\s]
I think that will make sure the string does not contain whitespace but I am unsure of how to also check to make sure it is not empty. Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
根据我的理解,您想要匹配非空白和非空字符串,因此最佳答案是做相反的事情。我建议:
这匹配任何包含至少一个非空白字符(中间的
\S
)的字符串。它的前后可以是任何内容、任何字符或空白序列(包括换行符):(.|\s)*
。您可以尝试一下 regex101 上的说明。
In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:
This matches any string containing at least one non-whitespace character (the
\S
in the middle). It can be preceded and followed by anything, any character or whitespace sequence (including new lines):(.|\s)*
.You can try it with explanation on regex101.
/^$|\s+/
如果匹配,则有空格或其为空。/^$|\s+/
if this matched, there's whitespace or its empty.大多数正则表达式引擎支持“对应部分”转义序列。也就是说,对于
\s
(空白),有其对应部分\S
(非空白)。使用此功能,您可以检查是否至少有一个带有
^\S+$
的非空白字符。PHP 的 PCRE 有几个这样的转义序列。
Most regular expression engines support "counter part" escape sequences. That is, for
\s
(white-space) there's its counter part\S
(non-white-space).Using this, you can check, if there is at least one non-white-space character with
^\S+$
.PCRE for PHP has several of these escape sequences.
<代码>/^$|\s+/
当空格或空格
/(?!^$)([^\s])/
时匹配当它不为空或空格时匹配
/^$|\s+/
This matches when empty or white spaces
/(?!^$)([^\s])/
This matches when its not empty or white spaces
我最终使用了与已接受的答案类似的内容,并进行了一些小的修改
Expresso 的解释
I ended up using something similar to the accepted answer, with minor modifications
Explanation by the Expresso
有点晚了,但我发现这是一个正则表达式,它返回 0 个空白或空白匹配项:
您可以在 regex101
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
You can test this out at regex101
/^[\s]*$/
匹配空字符串和仅包含空格的字符串/^[\s]*$/
matches empty strings and strings containing whitespaces only非空白和非空字符串的适当正则表达式应该是
灾难性回溯
这可以防止
.
和\s
具有重叠匹配的 。这显示在 regex101 中,测试字符串甚至只有 20 个左右的空格字符。The appropriate regex for a non-blank and non-empty string should be
This prevents catastrophic backtracking that
has with
.
and\s
having overlapping matching. This shows at regex101 with a test string of even just 20 or so space characters.它适用于我的情况。当字符串需要包含字符时,不能为空且不能包含空格
it works for my case. When it is necessary for a string to contain characters, not be empty and not contain spaces