简体   繁体   English

正则表达式验证并从字符串中提取数据

[英]Regex to validate and extract data from string

I'm trying to create 2 regex in .net c#. 我正在尝试在.net c#中创建2个正则表达式。

  1. Validate that the input that the user writes has the following format one or multiple times: 验证用户编写的输入具有以下格式一次或多次:

Sample: 样品:

/TEXT;dd-mm-yyyy;TEXT/TEXT;dd-mm-yyyy;TEXT/TEXT;dd-mm-yyyy;TEXT

Or 要么

/TEXT;dd-mm-yyyy;TEXT

At least 1 time should be entered. 至少应输入1次。 The middle part: dd-mm-yyyy should be day-month-year like 20-02-1997 In the parts TEXT there shouldn't be any / otherwise i accept that regex willfail. 中间部分:dd-mm-yyyy应该是类似于1997年2月20日的日-月-年。在文本部分中,不应有任何/否则我接受regex将失败。

  1. The second regex would be to extract the "groups". 第二个正则表达式将提取“组”。

I tried with: 我尝试过:

string test = "/TEXT;dd-mm-yyyy;TEXT/TEXT;dd-mm-yyyy;TEXT/TEXT;dd-mm-yyyy;TEXT";
            string reguexp = "[\\/(\\w+;\\w+;\\w+)+]";
            foreach (System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(test, reguexp))
            {
                Console.WriteLine("'{0}' found at index {1}.", match.Value, match.Index);
            }

However is not working as detects each character as a match and i would like to extract "groups" /TEXT;dd-mm-yyyy;TEXT one by one to later do any extra data process. 但是,由于无法检测到每个字符作为匹配项,因此我想一一提取“组” /TEXT;dd-mm-yyyy;TEXT ,以便以后进行任何额外的数据处理。

I tried to start with the second regex thinking that once i have this regex the other should be easier. 我尝试从第二个正则表达式开始,以为一旦我有了这个正则表达式,另一个就应该更容易了。

Any help is accepted. 任何帮助都可以接受。 Best regards 最好的祝福

You should use Groups: 您应该使用网上论坛:

var strRegex = @"(?<date>\d{2}-\d{2}-\d{4})+";
var myRegex = new Regex(strRegex, RegexOptions.None);
var strTargetString = @"01-02-2000;15-03-2018";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
    var dateString = myMatch.Groups["date"].Value;

    // TODO: Check dateString is valid date (e.g. with DateTime.TryParseExact(...))
}

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

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