正则表达式什么,但在C#中一个空字符串 [英] regular expression for anything but an empty string in c#

查看:270
本文介绍了正则表达式什么,但在C#中一个空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用正则表达式来检测任何不是一个空字符串是这样的:

 字符串S1 =; 
字符串s2 =;
串S3 =;
串S4 =;



等。



我知道我可以使用修剪等,但我想用正则表达式。



感谢。



基督教


解决方案

  ^(?! \s * $)+ 

将匹配含有至少一个非空字符的任意字符串



所以

 如果(Regex.IsMatch(subjectString,@^(?!\s * $)。+) ){
//匹配成功
}其他{
//匹配尝试失败
}

应该为你做这个。



^ 主播在搜索开始的字符串。



(?\s * $),所谓的积极的前瞻,声称这是不可能只匹配空格字符,直到字符串的结尾。



+ 然后将实际做这场比赛。它会匹配任何(除换行符)到字符串的结尾。如果你想允许换行,你必须将 RegexOptions.Singleline 选项。






从以前版本的问题遗留下来的:

  ^ \s * $ 

匹配只包含空白(或空)字符串。



正好相反:

  ^ \S + $ 

只匹配只包含非空格字符的字符串,一个字符最小。


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 = "   ";

etc.

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

Thanks.

Christian

解决方案

^(?!\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
}

should do this for you.

^ anchors the search at the start of the string.

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

.+ 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).

The exact opposite:

^\S+$

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

这篇关于正则表达式什么,但在C#中一个空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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