我想提取这个文件名中的数字部分。 “姓名,lastname_123456_state_city.pdf”用C中的Indexof提取字符串#
我有这么远..
idstring = file.Substring(file.IndexOf("_") + 1,
(file.LastIndexOf("_") - file.IndexOf("_") - 1));
我想提取这个文件名中的数字部分。 “姓名,lastname_123456_state_city.pdf”用C中的Indexof提取字符串#
我有这么远..
idstring = file.Substring(file.IndexOf("_") + 1,
(file.LastIndexOf("_") - file.IndexOf("_") - 1));
这是那些情况下,正则表达式可能是更好的一个:
_(\d+)_
而且,这里是如何你会用它
string input = "Name, lastname_123456_state_city.pdf";
string regexPattern = @"_(\d+)_";
Match match = Regex.Match(input, regexPattern, RegexOptions.IgnoreCase);
if (match.Success)
string yourNumber = match.Groups[1].Value;
谢谢你完成了这项工作。 – 2012-04-24 22:13:07
为什么不只是使用正则表达式?测试@"_([0-9]*)_"
应该做的伎俩。
var firstUnderscore = file.IndexOf("_");
var nextUnderscore = file.IndexOf("_", firstUnderscore + 1);
var idstring = file.Substring(firstUnderscore + 1, nextUnderscore - firstUnderscore - 1);
谢谢,我希望我可以选择两个答案! – 2012-04-24 22:15:02
你可以使用一个System.Text.RegularExpressions.Regex
var regex = new Regex(@"^.*_(?<number>\d+)_.*\.pdf");
var idstring=regex.Match(file).Groups["number"].Value;
威尔号永远是第一个破折号后?你可以在_上使用Split并且获取数组的第一个元素 – Sparky 2012-04-24 21:57:09