Skip to main content
 首页 » 编程设计

c#之String.Trim() 可以删除正则表达式\S 匹配的字符吗

2024年01月13日42thcjp

请帮助我理解以下是否可能:

var regexMatch = Regex.Match(inputString, "(\S*\d+\S*|\d)+"); 
 
if (regexMatch.Value == String.Empty) 
{ 
    return null; 
} 
else 
{ 
    var trimmedString = regexMatch.Value.Trim(); 
 
    if(trimmmedString != regexMatch.Value) 
    { 
        //Is there any value for inputString that makes this reachable? 
    } 
} 

请您参考如下方法:

从 .NET 4.0 开始,Trim 使用 Char.IsWhiteSpace 方法来决定修剪什么; documentation列出所有将被修剪的字符。由于 \S 的文档并未说明它使用相同的字符列表,因此询问是否存在不匹配是一个公平的问题。

找出答案的一种方法是详尽搜索:

var ws = new Regex("\\S"); 
for (char c = '\0'; c != 0xffff; c++) { 
    if (char.IsWhiteSpace(c)) { 
        var m = ws.Match("" + c); 
        if (m.Value.Length != 0) { 
            Console.Error.WriteLine("Found a mismatch: {0}", (int)c); 
        } 
    } 
} 

运行此代码不会产生任何结果:char.IsWhitespace 认为空白的 26 个字符中没有一个与正则表达式的 \S 匹配。因此我必须得出结论,受 trimmmedString != regexMatch.Value 条件保护的代码是无法访问的。

作为旁注,regexMatch.Value 永远不能为 null:according to the documentation ,

If a call to the Regex.Match or Match.NextMatch method fails to find a match, the value of the returned Match.Value property is String.Empty.

您可以删除第一个 if,或将其替换为与 String.Empty 的比较。