regular expression for anything but an empty string

前端 未结 9 916
予麋鹿
予麋鹿 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:06

    In .Net 4.0, you can also call String.IsNullOrWhitespace.

    0 讨论(0)
  • 2020-11-29 02:07
    ^(?!\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 negative 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.

    0 讨论(0)
  • 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?
    0 讨论(0)
提交回复
热议问题