regular expression for anything but an empty string

前端 未结 9 1024
予麋鹿
予麋鹿 2020-11-29 01:22

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


        
9条回答
  •  醉酒成梦
    2020-11-29 02:10

    You can do one of two things:

    • match against ^\s*$; a match means the string is "empty"
      • ^, $ are the beginning and end of string anchors respectively
      • \s is a whitespace character
      • * is zero-or-more repetition of
    • find a \S; an occurrence means the string is NOT "empty"
      • \S is the negated version of \s (note the case difference)
      • \S therefore matches any non-whitespace character

    References

    • regular-expressions.info, Anchors, Repetition
    • MSDN - Character classes - Whitespace character \s
      • Note that unless you're using RegexOptions.ECMAScript, \s matches things like ellipsis

    Related questions

    • .Net regex: what is the word character \w?

提交回复
热议问题