简体   繁体   English

正则表达式模式C#

[英]Regular Expression Pattern C#

I have the following string that would require me to parse it via Regex in C#. 我有以下字符串,需要我通过C#中的Regex对其进行解析。

Format: rec_mnd.rate.current_rate.sum. 格式:rec_mnd.rate.current_rate.sum。 QWD.RET : 214345 数量:214345

I would like to extract our the bold chars as group objects in a groupcollection. 我想将粗体字符提取为groupcollection中的组对象。

QWD = 1 group RET = 1 group 214345 = 1 group QWD = 1组RET = 1组214345 = 1组

what would the message pattern be like? 消息模式是什么样的?

It would be something like this: 就像这样:

string s = "Format: rec_mnd.rate.current_rate.sum.QWD.RET : 214345";
Match m = Regex.Match(s, @"^Format: rec_mnd\.rate\.current_rate\.sum\.(.+?)\.(.+?) : (\d+)$");
if( m.Success )
{
    Console.WriteLine(m.Groups[1].Value);
    Console.WriteLine(m.Groups[2].Value);
    Console.WriteLine(m.Groups[3].Value);
}

The question mark in the first two groups make that quantifier lazy: it will capture the least possible amount of characters. 前两组中的问号使该量词变得懒惰:它将捕获最少数量的字符。 In other words, it captures until the first . 换句话说,它捕获到第一个. it sees. 它看到了。 Alternatively, you could use ([^.]+) in those groups, which explicitly captures everything except a period. 另外,您可以在这些组中使用([^.]+) ,以明确捕获除句点以外的所有内容。

The last group explicitly only captures decimal digits. 最后一组明确地仅捕获十进制数字。 If your expression can have other values on the right side of the : you'd have to change that to .+ as well. 如果你的表达可能对的右侧其他值:你必须要改变,要.+为好。

Please, make it a lot easier on yourself and label your groups to make it easier to understand what is going on in code. 请给自己一个方便,并给组加上标签,以使他们更容易理解代码中正在发生的事情。

RegEx myRegex = new Regex(@"rec_mnd\.rate\.current_rate\.sum\.(?<code>[A-Z]{3})\.(?<subCode>[A-Z]{3})\s*:\s*(?<number>\d+)");

var matches = myRegex.Matches(sourceString);
foreach(Match match in matches)
{
    //do stuff
    Console.WriteLine("Match");
    Console.WriteLine("Code:    " + match.Groups["code"].Value);
    Console.WriteLine("SubCode: " + match.Groups["subCode"].Value);
    Console.WriteLine("Number:  " + match.Groups["number"].Value);
}

不管。之间是什么,这都应该为您提供所需的内容。

@"(?:.+\.){4}(.\w+)\.(\w+)\s?:\s?(\d+)"

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

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