C# regular expression: match the content of specified characters in a string

1 Functional requirements
  • match string
“m1.large(vcpu 2,ram 4G)|c95f5529-47e8-46d4-85da-319eb9905a9b”.
  • target string
vcpu: “2”,
ram: “4”,
id:“c95f5529-47e8-46d4-85da-319eb9905a9b”.

2 code implementation

using System;
using System.Text.RegularExpressions;

namespace RegexDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var flavorRef = "m1.large(vcpu 2,ram 4G)|c95f5529-47e8-46d4-85da-319eb9905a9b";

            Regex regex = new Regex(@"(?<= )[^ \,G]+(?=\,|G)|(?<=\|)[^\|]+");
            MatchCollection mc = regex.Matches(flavorRef);

            var cpu = mc[0].Value;      //cpu:2
            var ram = mc[1].Value;      //ram:4
            var id = mc[2].Value;     //flavorId:c95f5529-47e8-46d4-85da-319eb9905a9b

            Console.WriteLine("cpu:" + cpu + " " + "ram:" + ram + " " + "id:" + id);
            Console.ReadKey();
        }
    }
}


3 Regular Expression Specification Reference

+: Match the preceding subexpression one or more times. For example, "zo+" matches "zo" and "zoo", but not "z". + is equivalent to {1,}.

x|y: Match x or y. For example, "z|food" can match "z" or "food". "(z|f)ood" matches "zood" or "food".

[^xyz]: Set of negative characters. Matches any character not included. For example, " [^abc] " can match " p " in " plain ".

(?=pattern): Positive positive lookahead. For example, "Windows(?=95|98|NT|2000)" matches "Windows" in "Windows2000" .

(?<=pattern): Reverse positive lookahead. For example, "(?<=95|98|NT|2000)Windows" matches "Windows" in "2000Windows" .


4 Attachment: Regular Expression Reference Manual

http://tool.oschina.net/uploads/apidocs/jquery/regexp.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325356810&siteId=291194637