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"
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
asked Jan 8, 2010 at 13:58
MartGriff
2,8718 gold badges38 silver badges43 bronze badges
3 Answers 3
Use:
string s = "REF_SPHCPHJ0000057_Cancel Payer_20100105174151.pdf";
string middleBit = s.Split('_')[2];
Console.WriteLine(middleBit);
The output is
Cancel Payer
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
answered Jan 8, 2010 at 14:01
jason
243k36 gold badges437 silver badges532 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Igor Jerosimić
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.
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;
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
answered Jan 8, 2010 at 14:00
Rubens Farias
58k8 gold badges136 silver badges165 bronze badges
1 Comment
George Johnston
That seems like a bit of overkill to simply split a string.
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
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
answered Jan 8, 2010 at 14:19
Danail
10.6k12 gold badges58 silver badges76 bronze badges
Comments
lang-cs
.Split('_')[2]?