FirstAider
FirstAider

Reputation: 77

Extract value from a string in C# from a specific position

I have bunch of files in a folder and I am looping through them. How do I extract the value from the below example? I need the value 0519 only.

DOC 75-20-0519-1.PDF

The below code gives the complete part include -1.

Convert.ToInt32(Path.GetFileNameWithoutExtension(objFile).Split('-')[2]);

Appreciate any help.

Upvotes: 1

Views: 315

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can try regular expressions in order to match the value.

pattern:

 [0-9]+            - one ore more digits
 (?=[^0-9][0-9]+$) - followed by not a digit and one or more digits and end of string

code:

  using System.Text.RegularExpressions;

  ...

  string file = "DOC 75-20-0519-1.PDF";

  // "0519"
  string result = Regex
    .Match(Path.GetFileNameWithoutExtension(file), @"[0-9]+(?=[^0-9][0-9]+$)")
    .Value;

If Split('-') fails, and you have an entire string as a result, it seems that you have a wrong delimiter. It can be, say, one of the dashes:

  "DOC 75–20–0519–1.PDF";  // n-dash
  "DOC 75—20—0519—1.PDF";  // m-dash

Upvotes: 3

Mihir Dave
Mihir Dave

Reputation: 4014

You can use REGEX for this

Match match  = Regex.Match("DOC 75-20-0519-1.PDF", @"DOC\s+\d+\-\d+\-(\d+)\-\d+", RegexOptions.IgnoreCase);

string data = match.Groups[1].Value;

Upvotes: 0

Related Questions