c# - 如何使用 .Net Regex 匹配除 'just spaces' 之外的任何内容

标签 c# regex

我想匹配一个包含任何内容但不包含“仅空格”的字符串。

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

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

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

这是我的测试代码:

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

谢谢

最佳答案

我会用

^\s*\S+.*?$

分解正则表达式...

  • ^ - 行首
  • \s* - 零个或多个空白字符
  • \S+ - 一个或多个非空白字符
  • .*? - 任何字符(空格与否 - 非贪婪 -> 尽可能少地匹配)
  • $ - 行尾。

关于c# - 如何使用 .Net Regex 匹配除 'just spaces' 之外的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14834019/

相关文章:

c# - 如何使数据库更新为 'score record'?

javascript - Internet Explorer match() 无法正常工作

regex - perl 在 bash 中查找两个模式之间的模式

php - 正则表达式电子邮件 - 如何在电子邮件中允许加号?

c# - 从文件夹中选择随机文件

c# - 使用 Process.Start 在 C# 中打开文件

c# - 具有字符串参数的构造函数和具有对象参数的相同重载

c# - 创建带有启用/禁用按钮的登录表单

Javascript 使用正则表达式替换逗号分隔的字符

php - 如何使用 RegEx 匹配方括号文字?