views:

65

answers:

2

I have the below situation

Case 1:

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

Replace with: AP

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

Case 2:

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

Replace with: USD$

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

As can be make out that, always the ~<string> will be replaced.

Is it possible to achieve the same through regular expression?

Note:~ Nothing will be known at compile time except the structure. A typical structure

goes like

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

I am using C#3.0

A: 

Why not use string.Replace(string,string)?

Wesley Wiser
At compile time it will not known to me "AK" or "B$" .. So how can I apply that
priyanka.sarkar_2
+4  A: 

This simple regex will do it:

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

You can test it here:

http://regexhero.net/tester/

Select the tab Replace at RegexHero.

Enter ~(\w*[A-Z$]) as the Regular Expression.

Enter ~AP as the Replacement string.

Enter X(P)~AK,X(MV)~AK as the Target String.

You'll get this as the output:

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

In C# idiom, you'd have something like this:

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 + "]");
    }
}
Leniel Macaferi
Your program is great but fails in string text = "X(P)~%,X(MV)~%";string selecteditem = "KP";string result = Regex.Replace(text, @"~(\w*[A-Z$])", "~" + selecteditem);
priyanka.sarkar_2
Oh... add that percentile symbol % to the regex pattern. Like this: `~(\w*[A-Z$%])`
Leniel Macaferi