简体   繁体   English

正则表达式解析字符串

[英]Regular Expression to parse string

I have potential strings like this.我有这样的潜在strings The fist few characters are a symbol that can be one to a few letters, but could contain weird characters like "/".前几个characters是一个符号,可以是一个到几个字母,但可能包含奇怪的字符,如“/”。 Then the next six characters are always a date , YYMMDD where YY,MM,DD are always integers , but are always padded to the left with a 0 as shown.然后接下来的六个characters始终是date , YYMMDD 其中 YY,MM,DD 始终是integers ,但始终用0填充到左侧,如图所示。 This is followed by a single character that is always 'C' or 'P', then finally a double .后面是一个始终为 'C' 或 'P' 的单个字符,最后是一个double

AAPL220819C152.5
AAPL220819P195
AAPL220902P187.5
AAPL220819C155
AAPL220930C180

What is a regular expression that parses these strings into its constituent parts,将这些字符串parses为其组成部分的regular expression是什么,

Symbol,
Date,
COP,
Strike

fast ?

So the expected output would be:所以预期的 output 将是:

"AAPL220819C152.5" {Symbol = "AAPL", Date = 2022-08-19, COP = "C", Strike = 152.5 }
"AAPL220819P195"   {Symbol = "AAPL", Date = 2022-08-19, COP = "P", Strike = 195.0}

I have seen similar posts here but I don't understand enough to modify it.我在这里看到过类似的帖子,但我对修改它的理解还不够。

Try this:尝试这个:


        static void Main(string[] args)
        {
            TestParsingRegex("AAPL220819C152.5", "AAPL220819P195", "AAPL220902P187.5", "AAPL220819C155", "AAPL220930C180");
        }

        private static void TestParsingRegex(params string[] strings)
        {
            var regex = new Regex(@"([A-Z]+)(\d{6})([CP]{1})(.*)");
            foreach (var s in strings)
            {
                var match = regex.Match(s);
                foreach (var g in match.Groups)
                {
                    Console.WriteLine(g);
                }
            }
        }

it should have the following output:它应该有以下 output:

AAPL220819C152.5
AAPL
220819
C
152.5
AAPL220819P195
AAPL
220819
P
195
AAPL220902P187.5
AAPL
220902
P
187.5
AAPL220819C155
AAPL
220819
C
155
AAPL220930C180
AAPL
220930
C
180

Notice that the first group is the entire string请注意,第一组是整个字符串

This regex uses groups to get the desired parsing like so:此正则表达式使用组来获得所需的解析,如下所示:

([AZ]+) all upper case letters up to the next group ([AZ]+)所有大写字母直到下一组

(\d{6}) exactly six digits (\d{6})正好六位数

([CP]{1}) exactly one C or P character ([CP]{1})正好一个CP字符

(.*) everything else (.*)其他一切

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

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