我有以下代码:
Match matcher = new Regex("[0-9]+.[0-9]+.[0-9]+").Match("12/02/1994");
if (matcher.Success)
{
string matchedString1 = matcher.Value;
string matchedString2 = matcher.ToString();
}
在这种情况下,matchedString1
和matchedString2
包含相同的值"12/02/1994"
。 matcher.Value
和matcher.ToString()
是否始终为任何正则表达式返回相同的结果?
答案 0 :(得分:5)
Match类派生自Group类,该类派生自Capture类。
Capture类使用以下代码覆盖ToString()方法:
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
return this.Value;
}
所以,是的,它是相同的值。
答案 1 :(得分:2)
来自 MSDN ;
从输入字符串中获取捕获的子字符串。
通过调用,从输入字符串中检索捕获的子字符串 值属性。
即使我们查看 .NET Reflector ,我们也可以看到Capture
类覆盖ToString()
这样的方法;
[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public override string ToString()
{
return this.Value;
}
所以,是的。它们具有相同的价值。