如何每次都能可靠地提取“ 20130901”-请参见下面的代码?如果有匹配项,则可以解析为一个日期。其格式始终为yyyyMMdd
string s = "X23_CBW_13CP05AUGR1_20130901000000";
Regex rg = new Regex("\\d+");
Match m = rg.Match(s);
非常感谢
将正则表达式更改为仅提取8位数字序列,然后提取ParseExact
第一个匹配项:
string s = "X23_CBW_13CP05AUGR1_20130901000000";
Regex rg = new Regex(@"\d{8}");
Match m = rg.Match(s);
if (m.Success)
{
DateTime d = DateTime.ParseExact(m.Value, "yyyyMMdd",
CultureInfo.InvariantCulture);
// ...
// Do something with your value here
}
高级实施又称过度杀伤
如果您需要引擎查找第一个有效的日期字符串,即使它前面还有其他长数字序列,也可以实现:
string s = "X23CBW13992238455222348CP05AUGR120130901000000";
Regex rg = new Regex(@"\d{8,}");
MatchCollection mc = rg.Matches(s);
DateTime? d = null;
foreach (Match m in mc)
{
string digits = m.Value;
for (int n = 0; n < digits.Length - 8; n++)
{
try
{
d = DateTime.ParseExact(digits.Substring(n, 8), "yyyyMMdd",
CultureInfo.InvariantCulture);
break;
}
catch
{ }
}
if (d != null)
break;
}
if (d != null)
{
// Use your value here
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句