简体   繁体   中英

Extract text, hyphen and number from string

In work we use a Global Distribution System for bookings which is very very old, when we cancel a booking we get a response from their web service to say if the booking has been successfully cancelled.

The response contains a bool to say if it is cancelled or not and a string with any other info such as cancellation reference or why it could not be cancelled etc etc.

If it is successfully cancellled the cancellation reference is tied up in the middle of the string within the response and looks something like this

"NXT REPLACES  1  REDISPLAY ITINERARY1CXL-13113654 THANK YOU FOR YOUR INTEREST"

From this string I need to extract "CXL-13113654"...

Basically the CXL followed by the "-" then any character upto but not including the " "

I have searched university of google and everything I can find seems to be only extracting numbers, characters or symbols never a mixture within a set format like mine.

Can anyone help?

How can this be done?

正则表达式模式:

System.Text.RegularExpressions.Regex.Match(inputString, @"(?<match>CXL\-[^\s]+)").Groups["match"].Value

Assuming it's a single line search... you'll want a Regex like this....

(?<Anything>[^CXL[\s]*\-[\s]*[^\s]+)

This looks for CXL followed by white-space of any amount (0 or more), then a hyphen, then 0 or more whitespace, and then match all non whitespace. All of this will be put into the group called "Anything". You can test it on this page if you like .

The C# for this would then be...

// -- in using statements add this
using System.Text.RegularExpressions;

// -- in your code add something like this

var inputString = "NXT REPLACES  1  REDISPLAY ITINERARY1CXL-13113654 THANK YOU FOR YOUR INTEREST";
var match = Regex.Match(inputString, @"(?<Anything>CXL[\s]*\-[\s]*[^\s]+) ");
if(match.success && match.Groups["Anything"].Success)
{
  var anything = match.Groups["Anything"].Value;
  // -- do something with anything
}
using System;
using System.Text.RegularExpressions;

class Program
{
    public static void Main()
    {
        var input = "NXT REPLACES 1 REDISPLAY ITINERARY1CXL-13113654 THANK YOU FOR YOUR INTEREST";
        var match = Regex.Match(input, @"CXL\-(?<number>\d+)\s+");
        if (match.Success)
        {
            Console.WriteLine(match.Groups["number"]);
        }
    }
}

prints:

13113654

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