我想提取這個文件名中的數字部分。 「姓名,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