regular expression for anything but an empty string

前端 未结 9 1009
予麋鹿
予麋鹿 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 01:54

    We can also use space in a char class, in an expression similar to one of these:

    (?!^[ ]*$)^\S+$
    (?!^[ ]*$)^\S{1,}$
    (?!^[ ]{0,}$)^\S{1,}$
    (?!^[ ]{0,1}$)^\S{1,}$
    

    depending on the language/flavor that we might use.

    RegEx Demo

    Test

    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
        public static void Main()
        {
            string pattern = @"(?!^[ ]*$)^\S+$";
            string input = @"
    
                abcd
                ABCD1234
                #$%^&*()_+={}
                abc def
                ABC 123
                ";
            RegexOptions options = RegexOptions.Multiline;
    
            foreach (Match m in Regex.Matches(input, pattern, options))
            {
                Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
            }
        }
    }
    

    C# Demo


    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


    RegEx Circuit

    jex.im visualizes regular expressions:

提交回复
热议问题