Regex - Match String That Does Not Contain Only Spaces

时间:2018-01-23 19:41:13

标签: regex

I am looking for a regex expression that will return true if the string does not contain only spaces. My attempt so far is ^[^ \s]*$ but it does not pick up on strings that contains multiple words.

I want to be clear that I am trying to match a string that does not contain only spaces.

Test case:

'apple'                true
'apple banana'         true
'apple banana orange'  true
' apple banana'        true
'  apple banana'       true
' '                    false
'  '                   false
'   '                  false

4 个答案:

答案 0 :(得分:2)

You might very well get along with:

^(?!\s+$).+

See a demo on regex101.com.


Broken down, this says:

^         # start of the line / string
(?!\s+$)  # neg. lookahead, making sure there are not only whitespaces
.+        # at least one character, possibly more

答案 1 :(得分:2)

  • 使用\S匹配非空格字符
  • 在非空格
  • 之前和之后留出空格

例如:

^\s*\S.*$

答案 2 :(得分:2)

预先考虑非空间:

Blocked loading mixed active content “dev.mysite.com/fileadmin/templates/fonts/glyphicons-halflings-regular.woff2”
[Learn More]
jquery-1.11.3.min.js:4:24860
Blocked loading mixed active content “dev.mysite.com/fileadmin/templates/fonts/fontawesome-webfont.woff2?v=4.7.0”
[Learn More]
jquery-1.11.3.min.js:4:24860

关于展望未来的好处是你可以将它们叠加起来以结合可能难以作为直接正则表达式编写的无关断言。例如,假设我们想要添加一个没有数字的断言:

^(?=.*\S).*

将它写成一个简单的正则表达式是很尴尬的,而且这与正则表达式一样可读 - 前瞻性与彼此和主正则表达式是分开的。

答案 3 :(得分:0)

最简单的正则表达式是:

\S

它将匹配包含非空白字符的任何字符串。