匹配非空白字符的正则表达式 [英] Regular Expression to Match Non-Whitespace Characters
问题描述
我需要制作一个匹配以下内容的正则表达式:
I need to make a regular expression that matches something like:
JG2144-141/hello
或
!
但不是:
laptop bag
或仅由空白字符组成的字符串 (' '
).
or a string consisting of whitespace chars only (' '
).
现在我有 [A-Za-z0-9-!/\S]
,但它不起作用,因为它仍然单独与笔记本电脑和包匹配.它根本不应该匹配笔记本电脑包和空字符串.
Right now I have [A-Za-z0-9-!/\S]
, but it isn't working because it still matches with laptop and bag individually. It shouldn't match laptop bag and the empty string at all.
推荐答案
[A-Za-z0-9-!/\S]
中的\S
使得此字符类等于 \S
,但您要确保字符串中的所有字符都是非空白字符.这就是为什么你应该用 ^
和 $
锚包裹模式并在 \S
之后添加一个 +
量词到匹配 1 个或多个此子模式.
The \S
in [A-Za-z0-9-!/\S]
makes this character class equal to \S
, but you want to make sure all chars in the string are non-whitespace chars. That is why you should wrap the pattern with ^
and $
anchors and add a +
quantifier after \S
to match 1 or more occurrences of this subpattern.
你可以使用
^\S+$
查看正则表达式演示
详情
^
- 字符串的开始\S+
- 1 个或多个非空白字符$
- 字符串结束.
^
- start of string\S+
- 1 or more non-whitespace chars$
- end of string.
这篇关于匹配非空白字符的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!