开发者

Extract a purchase order # from a string in C# and put it in another string

I have data stored in strings that I need to extract and turn into another string. My string data looks like this:

Widget PO NO. 1234

Body PO NO. 123456

Wing PO NO. 12345-2

Nut PO NO. 1-234-56-7

"PO NO." will always be the same, so I just want to extract the data after the trailing space in "NO. ", and turn it into another string so I can have 开发者_开发知识库the numeric data (i.e the purchase order #).

Thanks.


Using your actual string representations you have a space after each textual portion...so to provide yet another route...

String rawPO = "Body PO NO. 123456";
String trimmedPO = rawPO.Remove(0, rawPO.LastIndexOf(" ")).Trim();


        const string refString = "PO NO.";
        string aLine = "Widget PO NO. 1234";

        string orderNumb = aLine.Substring(aLine.LastIndexOf(refString) + refString.Length).Trim();


You can use Regular Expressions:

       Match m = Regex.Match(str, @"PO NO\. (?<PO>\d+)$");
       string poNumber = m.Groups["PO"].Value;


Try String.Split:

strOrder = "Widget PO NO. 1234";
arSplit = strOrder.Split(" PO NO. ");

This creates an array arsplit[] with everything before PO NO. in arSplit[0] and everything after in arsplit[1].


Use a Regular Expression to extract the parts you need. This regular expression will return grouped results:

[.\W]*PO NO\.\W*([\d-]*)

Here's some demo code (C#):

string[] strings = new string[] {"Widget PO NO. 1234",
                            "Body PO NO. 123456",
                            "Wing PO NO. 12345-2",
                            "Nut PO NO. 1-234-56-7"};
Regex regex = new Regex(@"[.\W]*PO NO\.\W*([\d-]*)");
Match match;

foreach (string s in strings)
{
    match = regex.Match(s);
    Console.WriteLine(match.Groups[1].Value);
}


string order = orders.Split(" ")[3];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜