我想匹配一个字符串,当它包含任何东西,但不是'只有空格'.
空间很好,只要还有别的东西,就可以在任何地方.
当空间出现在任何地方时,我似乎无法获得匹配.
(编辑:我希望在正则表达式中执行此操作,因为我最终希望将其与其他正则表达式模式结合使用|)
这是我的测试代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了这个输出:
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=''
Run Code Online (Sandbox Code Playgroud)
我想要的是这个:
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
Run Code Online (Sandbox Code Playgroud)
谢谢
我用了
^\s*\S+.*?$
Run Code Online (Sandbox Code Playgroud)
打破正则表达式......
^ - 开始行\s* - 零个或多个空白字符\S+ - 一个或多个非空白字符.*? - 任何字符(空白与否 - 非贪婪 - >尽可能少匹配)$ - 行结束.这里不需要正则表达式.您可以使用string.IsNullOrWhitespace()
正则表达式是这样的:
[^ ]
Run Code Online (Sandbox Code Playgroud)
这样做很简单:它检查你的字符串是否包含任何不是空格的东西.
我通过添加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));
}
Run Code Online (Sandbox Code Playgroud)
结果将是:
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
Run Code Online (Sandbox Code Playgroud)
BTW:而不是new Regex(r).Match(s)你应该使用Regex.Match(s, r).这允许正则表达式引擎缓存模式.