开发者

Make new string from old string, C#

开发者 https://www.devze.com 2023-01-11 10:28 出处:网络
Input: X(P)~AK,X(MV)~AK Expected Output: P(curr=AK),MV(curr=AK) Using C#3.0 I solved by using string functions(split,th开发者_开发问答en appending etc.)

Input:

X(P)~AK,X(MV)~AK

Expected Output:

P(curr=AK),MV(curr=AK)

Using C#3.0

I solved by using string functions(split,th开发者_开发问答en appending etc.)

Looking for more niche solution(like regular expression)

Thanks


var output = Regex.Replace(input, @"X\(([A-Z]+)\)~([A-Z]+)", "$1(curr=$2)");

This will replace all occurrences of X(something1)~something2 with something1(curr=something2). All "something"s are assumed to be sequences of uppercase characters.


A possible solution using regex. It's not the cleanest, but you could go from here.

string process(string s)
{
    string ret = "";
    System.Text.RegularExpressions.Regex r = new Regex(@"X\(([A-Z]+)\)~([^,]+)\,?");
    bool first = true;
    foreach (Match m in r.Matches(s))
    {
        ret += (first ? "" : ",") + m.Groups[1] + "(curr=" + m.Groups[2] + ")";
        first = false;
    }
    return ret;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消