Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting string with Indexof in c#

Tags:

c#

indexof

I am trying to extract the number portion in this filename. "Name, lastname_123456_state_city.pdf"

I have got this far..

idstring = file.Substring(file.IndexOf("_") + 1, 
    (file.LastIndexOf("_") - file.IndexOf("_") - 1));
like image 326
Allan Jason Avatar asked Feb 21 '23 17:02

Allan Jason


1 Answers

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;
like image 121
Justin Pihony Avatar answered Mar 07 '23 21:03

Justin Pihony