3

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

1
  • 1
    Your question has nothing to do with C# - not C#3.0 nor any other. Your question has to do with .NET, which is where the regular expression support is. There is no regular expression support in C#. Commented Aug 12, 2010 at 2:58

2 Answers 2

5

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 + "]");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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);
Oh... add that percentile symbol % to the regex pattern. Like this: ~(\w*[A-Z$%])
0

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

1 Comment

At compile time it will not known to me "AK" or "B$" .. So how can I apply that