6

I have a string value which I need to get the middle bit out of, e.g. "Cancel Payer" / "New Paperless".

These are examples of the string format:

"REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf"
"REF_SPHCPHJ0000056_New Paperless_20100105174151.pdf"

1
  • 4
    Seems to me that it is the 3rd element ([2]) of the split operation? What problem are you having with calling .Split('_')[2] ? Commented Jan 8, 2010 at 13:59

3 Answers 3

16

Use:

string s = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middleBit = s.Split('_')[2];
Console.WriteLine(middleBit);

The output is

Cancel Payer
Sign up to request clarification or add additional context in comments.

1 Comment

Jason's solution will not work correctly in case there is an underscore in the "middle bit". It will return only the part before underscore.
5

This is a place for regular expressions:

Regex re = new Regex(@".*_(?<middle>\w+ \w+)_.*?");
string name = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middle = re.Match(name).Groups["middle"].Value;

1 Comment

That seems like a bit of overkill to simply split a string.
0

I think that the regular expression

Regex re = new Regex(@"\w+_\w+_(?<searched>.*)_\d*.pdf");

will meet your needs, if the PDF files always come to you as:

REF_<text>_<your text here>_<some date + id maybe>.pdf

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.