gpt4 book ai didi

c# - 使用正则表达式忽略空字符串和空格

转载 作者:行者123 更新时间:2023-12-02 22:34:33 28 4
gpt4 key购买 nike

我有以下简单的测试,由于某种原因没有返回 true。

string[] test = new string[] { "A", " ", " ", "D", "" };
Regex reg = new Regex(@"^[A-Z]\s$");
bool ok = test.All(x => reg.IsMatch(x));

我也尝试过将\s 放在方括号内,但这也不起作用

我想确保数组中所有非空或空格的字符都匹配 A-Z。

我意识到我可以在 All 之前执行Where(x=>!String.IsNullorEmpty(x) && x != ""),但我认为正则表达式可以处理这种情况

最佳答案

我想你想要:

Regex reg = new Regex(@"^[A-Z\s]*$");

这基本上是说“字符串完全由空格或 A-Z 组成”。

如果你想强制为单个字符或为空,只需将其更改为:

Regex reg = new Regex(@"^[A-Z\s]?$");

关于c# - 使用正则表达式忽略空字符串和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6585705/

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