简体   繁体   English

字符串宏替换

[英]string macro replacement

I have a Visual Studio 2008 C# .NET 3.5 application where I need to parse a macro. 我有一个Visual Studio 2008 C#.NET 3.5应用程序,需要在其中解析一个宏。

Given a serial serial number that is N digits long, and a macro like %SERIALNUMBER3% , I would like this parse method to return only the first 3 digits of the serial number. 给定一个序列号,该序列号为N位数字,并使用%SERIALNUMBER3%类的宏,我希望此解析方法仅返回序列号的前3位。

string serialnumber = "123456789";
string macro = "%SERIALNUMBER3%";
string parsed = SomeParseMethod(serialnumber, macro);

parsed = "123"

Given `%SERIALNUMBER7%, return the first 7 digits, etc.. 给定%SERIALNUMBER7%,则返回前7位,依此类推。

I can do this using String.IndexOf and some complexity, but I wondered if there was a simple method. 我可以使用String.IndexOf和一些复杂性来做到这一点,但我想知道是否有一个简单的方法。 Maybe using a Regex replace. 也许使用正则Regex替换。

What's the simplest method of doing this? 最简单的方法是什么?

var str = "%SERIALNUMBER3%";
var reg = new Regex(@"%(\w+)(\d+)%");
var match = reg.Match( str );
if( match.Success )
{
    string token = match.Groups[1].Value;
    int numDigits = int.Parse( match.Groups[2].Value );
}

Use the Regex class. 使用Regex类。 Your expression will be something like: 您的表情将类似于:

@"%(\w)+(\d)%"

Your first capture group is the ID (in this case, "SERIALNUMBER"), and your second capture group is the number of digits (in this case, "3"). 您的第一个捕获组是ID(在这种情况下为“ SERIALNUMBER”),而第二个捕获组是位数(在这种情况下为“ 3”)。

Very quick and dirty example: 非常快速和肮脏的示例:

static void Main(string[] args)
        {
            string serialnumber = "123456789";
            string macro = "%SERIALNUMBER3%";

            var match = Regex.Match(macro, @"\d+");

            string parsed = serialnumber.Substring(0, int.Parse(match.ToString()));
        }

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

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