4

当字符串包含任何内容但不包含“仅空格”时,我想匹配它。

空间很好,只要有其他东西,就可以在任何地方。

当空间出现在任何地方时,我似乎无法匹配。

(编辑:我希望在正则表达式中执行此操作,因为我最终想将它与其他正则表达式模式结合使用 | )

这是我的测试代码:

class Program
{
    static void Main(string[] args)
    {
        List<string> strings = new List<string>() { "123", "1 3", "12 ", "1  " , "  3", "   "};

        string r = "^[^ ]{3}$";
        foreach (string s in strings)
        {
            Match match = new Regex(r).Match(s);
            Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}'", s, r, match.Value));
        }
        Console.Read();
    }
}

这给出了这个输出:

string='123', regex='^[^ ]{3}$', match='123'
string='1 3', regex='^[^ ]{3}$', match=''
string='12 ', regex='^[^ ]{3}$', match=''
string='1  ', regex='^[^ ]{3}$', match=''
string='  3', regex='^[^ ]{3}$', match=''
string='   ', regex='^[^ ]{3}$', match=''

我想要的是这样的:

string='123', regex='^[^ ]{3}$', match='123' << VALID
string='1 3', regex='^[^ ]{3}$', match='1 3' << VALID
string='12 ', regex='^[^ ]{3}$', match='12 ' << VALID
string='1  ', regex='^[^ ]{3}$', match='1  ' << VALID
string='  3', regex='^[^ ]{3}$', match='  3' << VALID
string='   ', regex='^[^ ]{3}$', match=''    << NOT VALID

谢谢

4

3 回答 3

7

我会用

^\s*\S+.*?$

打破正则表达式...

  • ^- 线的开始
  • \s*- 零个或多个空白字符
  • \S+- 一个或多个非空白字符
  • .*?- 任何字符(空格与否 - 非贪婪 -> 尽可能少地匹配)
  • $- 行结束。
于 2013-02-12T14:04:18.647 回答
6

这里不需要正则表达式。您可以使用string.IsNullOrWhitespace()

一个正则表达式是这样的:

[^ ]

这样做很简单:它检查您的字符串是否包含任何不是空格的内容。

match.Success我通过添加到输出稍微调整了您的代码:

var strings = new List<string> { "123", "1 3", "12 ", "1  " , "  3", "   ", "" };

string r = "[^ ]";
foreach (string s in strings)
{
    Match match = new Regex(r).Match(s);
    Console.WriteLine(string.Format("string='{0}', regex='{1}', match='{2}', " +
                                    "is match={3}", s, r, match.Value,
                                    match.Success));
}

结果将是:

string='123', regex='[^ ]', match='1', is match=True
string='1 3', regex='[^ ]', match='1', is match=True
string='12 ', regex='[^ ]', match='1', is match=True
string='1  ', regex='[^ ]', match='1', is match=True
string='  3', regex='[^ ]', match='3', is match=True
string='   ', regex='[^ ]', match='', is match=False
string='', regex='[^ ]', match='', is match=False

顺便说一句:而不是new Regex(r).Match(s)你应该使用Regex.Match(s, r). 这允许正则表达式引擎缓存模式。

于 2013-02-12T13:47:46.900 回答
0

使用^\s+$并简单地否定 的结果Match()怎么样?

于 2013-02-12T13:48:11.277 回答