简体   繁体   English

从字符串中提取文本,连字符和数字

[英]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"... 从这个字符串中,我需要提取“ CXL-13113654” ...

Basically the CXL followed by the "-" then any character upto but not including the " " 基本上是CXL,后跟“-”,然后是任何字符,但不包括“”

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. 我已经搜索过Google大学,而我所能找到的一切似乎都只是在提取数字,字符或符号,而从未提取像我这样的固定格式内的混合形式。

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. 这将查找CXL,后跟任意数量的空格(0或更多),然后是连字符,然后是0或更多的空格,然后匹配所有非空格。 All of this will be put into the group called "Anything". 所有这些都将放入名为“ Anything”的组中。 You can test it on this page if you like . 如果愿意,可以在此页上进行测试

The C# for this would then be... C#为此将是...

// -- 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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