JOE SKEET
JOE SKEET

Reputation: 8098

c# easiest way to extract substring

i have a string:

string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

Upvotes: 1

Views: 535

Answers (3)

jeroenh
jeroenh

Reputation: 26772

This regex does the trick for the input string you provided:

        var input = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY";

        var pattern = @".*\\(\d{5})-";

        var result = Regex.Match(input, pattern).Groups[1].Value;

But I actually like Brad's solution using Path.GetFileName more :-)

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37523

Try (based on your answer in the comments about the \ character):

string result = myString.SubString(myString.LastIndexOf(@"\") + 1, 5);

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101594

String result = Path.GetFileName("\\\\Tecan1\\tecan #1 output\\15939-E.ESY").Split('-')[0];

Perhaps?

Upvotes: 14

Related Questions