简体   繁体   中英

How to extract a substring from a random string?

I have strings similar to these:

TAMPA HQ - 9125 Henderson Rd - Comment Posted on Work Order # 7065

TAMPA HQ - 9125 Henderson Rd - Work Order # 79651 Alert

TAMPA HQ - 9125 Henderson Rd - Work Order # 805923 Request Number Assigned

Is there any generic way to extract WO #? in C# so the output would be:

Work Order # 7065

Work Order # 79651

Work Order # 805923

etc?

This regex would work: Work Order # \\d+ .

Regex r = new Regex("Work Order # \d+");
Match match = r.Match("TAMPA HQ - 9125 Henderson Rd - Work Order # 79651 Alert");

使用这样的正则表达式:

"^Work Order #.\d+"

Here's an algorithm:

LengthOfString = StrLength (IncomingString)
WorkOrderNumberPosition = FindInString (IncomingString, "Work Order # ")
LeftSideRemovedString = SubString (IncomingString, WorkOrderNumberPosition, LengthOfString - WorkOrderNumberPosition)
WorkOrderRemoved = Replace (LeftSideRemovedString, "Work Order #", "")

Now, loop through and find the last consecutive character that is a number, and use that number to do a substring.

//to simulate an input lines
var input = new StringBuilder();
input.AppendLine("TAMPA HQ -9125 Henderson Rd -Comment Posted on Work Order # 7065");
input.AppendLine("TAMPA HQ -9125 Henderson Rd -Work Order # 79651 Alert");
input.AppendLine("TAMPA HQ - 9125 Henderson Rd -Work Order # 805923 Request Number Assigned");

Regex regex = new Regex(@"(?<Identifier>Work Order # \d+)");
var results = regex.Matches(input.ToString());
foreach (Match match in results)
{
    Console.WriteLine(match.Groups["Identifier"].Value);
}

tested here : http://rextester.com/CAR42027

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