除空字符串外的任何内容的正则表达式 [英] regular expression for anything but an empty string

查看:105
本文介绍了除空字符串外的任何内容的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用正则表达式来检测不是这样的空字符串的任何东西:

Is it possible to use a regular expression to detect anything that is NOT an "empty string" like this:

string s1 = "";
string s2 = " ";
string s3 = "  ";
string s4 = "   ";

等。

我知道我可以使用trim等。但是我想使用正则表达式。

I know I could use trim etc. but I would like to use a regular expression.

推荐答案

^(?!\s*$).+

将匹配包含至少一个非字符串的任何字符串,

will match any string that contains at least one non-space character.

So

if (Regex.IsMatch(subjectString, @"^(?!\s*$).+")) {
    // Successful match
} else {
    // Match attempt failed
}

应该为您做到这一点。

^ 将搜索锚定在字符串的开头。

^ anchors the search at the start of the string.

(?! \s * $),即所谓的负先行,断言只有到字符串末尾才能匹配空格字符。

(?!\s*$), a so-called negative lookahead, asserts that it's impossible to match only whitespace characters until the end of the string.

。+ 会真正进行匹配。它将匹配直到字符串末尾的所有内容(换行符除外)。如果要允许换行,则必须设置 RegexOptions.Singleline 选项。

.+ will then actually do the match. It will match anything (except newline) up to the end of the string. If you want to allow newlines, you'll have to set the RegexOptions.Singleline option.

从上一版本的问题开始查找:

Left over from the previous version of your question:

^\s*$

匹配仅包含空格(或为空)的字符串。

matches strings that contain only whitespace (or are empty).

正好相反:

^\S+$

仅匹配仅包含非空格字符且最少一个字符的字符串。

matches only strings that consist of only non-whitespace characters, one character minimum.

这篇关于除空字符串外的任何内容的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆