正则表达式检查字符串是否只有空格

cha*_*a89 5 regex postgresql

我想要一个正则表达式来检查字符串是否只有空格。

例子: ” ”

我目前正在使用这个正则表达式

[/^ *$/]
Run Code Online (Sandbox Code Playgroud)

但它也会检测其中包含单词的字符串。

示例:“abc xyz”

我想在 postgresql 函数中使用这个正则表达式,如下所示

IF r.colmn IS NULL  OR CAST(r.colmn as text) = '' 
       OR CAST(r.colmn as text) ~ '[/^ *$/]' -- regex not working
THEN
     RAISE NOTICE 'Do something';       
END IF;
Run Code Online (Sandbox Code Playgroud)

我可以在 postgresql 函数中使用任何正则表达式,该函数仅检查仅包含空格的字符串吗?

anu*_*ava 4

您需要从正则表达式中删除[/和/]:

IF r.colmn IS NULL  OR CAST(r.colmn as text) = '' 
       OR CAST(r.colmn as text) ~ '^ *$'
THEN
     RAISE NOTICE 'Do something';       
END IF;
Run Code Online (Sandbox Code Playgroud)

  • @UsamaTahir `'^\s*$'`,其中 `\s` 匹配任何空白,包括 `new line`。如果您只需要 `space` 和 `newline`,您可以执行 `'^[ \n]*$'`,但请记住,在 Windows 环境中您可能还需要 `'^[ \n\r]*$ '`,如果你想捕获选项卡等怎么办。我会推荐 `\s` 解决方案。https://regexone.com/lesson/whitespaces (4认同)