C# 在c中使用Indexof提取字符串#
我正在尝试提取此文件名中的数字部分。“姓名,姓氏\u 123456\u state\u city.pdf” 我已经走了这么远C# 在c中使用Indexof提取字符串#,c#,indexof,C#,Indexof,我正在尝试提取此文件名中的数字部分。“姓名,姓氏\u 123456\u state\u city.pdf” 我已经走了这么远 idstring = file.Substring(file.IndexOf("_") + 1, (file.LastIndexOf("_") - file.IndexOf("_") - 1)); 这是正则表达式可能更好的情况之一: _(\d+)_ 下面是您将如何使用它 string input = "Name, lastname_123456_st
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;
为什么不直接使用正则表达式呢?测试
@([0-9]*)。
应该可以做到这一点。您可以使用系统.Text.RegularExpressions.Regex
var firstUnderscore = file.IndexOf("_");
var nextUnderscore = file.IndexOf("_", firstUnderscore + 1);
var idstring = file.Substring(firstUnderscore + 1, nextUnderscore - firstUnderscore - 1);
var regex = new Regex(@"^.*_(?<number>\d+)_.*\.pdf");
var idstring=regex.Match(file).Groups["number"].Value;
var regex=new regex(@“^.*.(?\d+).*\.pdf”);
var idstring=regex.Match(文件).Groups[“number”].Value;
第一个破折号后面是否总是数字?你可以使用Split on u并抓住ArrayTanks的第一个元素,我希望我能选择两个答案!