简体   繁体   中英

Split string value in C#

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

These are examples of the string format:

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

Use:

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

The output is

Cancel Payer

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM