[英]extracting string with Indexof in c#
I am trying to extract the number portion in this filename. 我试图提取此文件名中的数字部分。 "Name, lastname_123456_state_city.pdf"
“姓名,lastname_123456_state_city.pdf”
I have got this far.. 我到目前为止..
idstring = file.Substring(file.IndexOf("_") + 1,
(file.LastIndexOf("_") - file.IndexOf("_") - 1));
This is one of those cases where a regex might be better: 这是正则表达式可能更好的情况之一:
_(\d+)_
And, here is how you would use it 而且,这是你如何使用它
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;
var firstUnderscore = file.IndexOf("_");
var nextUnderscore = file.IndexOf("_", firstUnderscore + 1);
var idstring = file.Substring(firstUnderscore + 1, nextUnderscore - firstUnderscore - 1);
Why not just use a regular expression? 为什么不使用正则表达式? Testing for
@"_([0-9]*)_"
should do the trick. 测试
@"_([0-9]*)_"
应该可以解决问题。
You could use a System.Text.RegularExpressions.Regex
您可以使用
System.Text.RegularExpressions.Regex
var regex = new Regex(@"^.*_(?<number>\d+)_.*\.pdf");
var idstring=regex.Match(file).Groups["number"].Value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.