C#Regex以字开头,以数字结尾

时间:2017-02-22 07:16:16

标签: c# regex string

我想帮助在C#中使用正则表达式来获取这些字符串

1) UserID.......: 21208
2) Customer.: 4340837
3) Password.........: 21208

2 个答案:

答案 0 :(得分:0)

您的示例中填充了“。”和“:”。我猜他们是可选的。 你能试试这个正则表达式吗?

^([a-zA-Z]{1,})([\.:\s]{1,})?([0-9]{1,})$
^([\w]{1,})([\.:\s]{1,})?([\d]{1,})$

从开始只是字母,组1中的a-Z。在组2中选择此点和空格。而在其余部分中仅包含组3中的数字。 第二个正则表达式是相同的,但有短线。第一个正则表达式更明确。

答案 1 :(得分:0)

如果你有固定的关键字,我会把它们放在一个集合中,并通过它匹配每个单独的一个:

string input = "Hi!. Thank you for contacting us regarding user ID and UserID for xxxx! UserID .......: 21208 Customer Number .: 4340837 Password .........: 21208 .... Contact: Attention! Customer will ensure that the User ID field that is not used by people who do not have access to the system. To ensure that all functions of xxxxx working properly, the customer must use Microsoft Internet Explorer 9.0 or Firefox 3.6 or later. If a previous version or another product, you may experience problems ";

string[] matches = {"UserID", "Customer Number", "Password"};

List<string> results = new List<string>();

foreach (var m in matches)
{   
    Match mat = Regex.Match(input, m+@"\s(\.*\:)(\s\d*)");

    results.Add (m+ mat.Groups[2].Value);
}


Console.WriteLine(String.Join(Environment.NewLine, results));

基本上这里有3组匹配。第三组有您正在寻找的数字。第二个是圆点。第一个是与关键字+点+数字的不良匹配。

相关问题