gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:07:58 26 4
gpt4 key购买 nike

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

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

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

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

这是我的测试代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com