Replace string with regular expression
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
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 + "]");
}
}
Why not use string.Replace(string,string)?
精彩评论