Replace string with regular expression

I have the following situation

Case 1:

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

Replaced by: AP

Conclusion: X(P)~AP,X(MV)~AP

Case 2:

Input: X(PH)~B$,X(PL)~B$,X(MV)~AP

Replace with :USD$

Conclusion: X(PH)~USD$,X(PL)~USD$,X(MV)~USD$

As you can understand, it is always replaced ~<string>.

Is it possible to achieve the same by regular expression?

Note: ~ During compilation, except for the structure, nothing will be known. Typical structure

looks like

X(<Variable Name>)~<Variable Name>

I am using C # 3.0

+3
source share
2 answers

This simple regex will do this:

~(\w*[A-Z$])

You can check it out here:

http://regexhero.net/tester/

Select the Replace tab in RegexHero.

Enter ~(\w*[A-Z$])as a regular expression.

~AP .

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

:

X(P)~AP,X(MV)~AP

# idiom - :

class RegExReplace
{
    static void Main()
    {
        string text = "X(P)~AK,X(MV)~AK";

        Console.WriteLine("text=[" + text + "]");

        string result = Regex.Replace(text, @"~(\w*[A-Z$])", "~AP");

        // Prints: [X(P)~AP,X(MV)~AP]
        Console.WriteLine("result=[" + result + "]");

        text = "X(PH)~B$,X(PL)~B$,X(MV)~AP";

        Console.WriteLine("text=[" + text + "]");

        result = Regex.Replace(text, @"~(\w*[A-Z$])", "~USD$");

        // Prints: [X(PH)~USD$,X(PL)~USD$,X(MV)~USD$]
        Console.WriteLine("result=[" + result + "]");
    }
}
+5

string.Replace(string, string)?

0

Source: https://habr.com/ru/post/1759254/


All Articles