tags:

views:

52

answers:

3

Consider the below

Case 1: [Success]

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

Replace with: AP

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

Case 2: [Failure]

Input: X(P)~$B,X(MV)~$B

Replace with: C$

Output: X(P)~C$,X(MV)~C$

Actual Output: X(P)~C$B,X(MV)~C$B

I am using the below REGEXP

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

This works fine for case 1 but falied for the second.

Need help

I am using C#3.0

Thanks

+3  A: 

It's unclear what exactly your matching requirements are, but changing the regex to @"~(\w*[A-Z$%]+)" should do the trick. (For the examples given, just plain @"~([A-Z$%]+)" should work too.)

LukeH
+1  A: 

It looks like you want something like this:

public static String replaceWith(String input, String repl) {
  return Regex.Replace(
     input,
     @"(?<=~)[A-Z$%]+",
     repl
  );
}

The (?<=…) is what is called a lookbehind. It's used to assert that to the left there's a tilde, but that tilde is not part of the match.

Now we can test it as follows (as seen on ideone.com):

Console.WriteLine(replaceWith(
  "X(P)~AK,X(MV)~AK", "AP"
));
// X(P)~AP,X(MV)~AP

Console.WriteLine(replaceWith(
  "X(P)~$B,X(MV)~$B", "C$"
));
// X(P)~C$,X(MV)~C$

Console.WriteLine(replaceWith(
  "X(P)~THIS,X(MV)~THAT", "$$$$"
));
// X(P)~$$,X(MV)~$$

Note the last example: $ is a special symbol in substitutions and can have special meanings. $$ actually gets you one dollar sign.

Related questions

polygenelubricants
A: 

Your expression (being greedy) replaces the first string that starts with zero or more work characters that ends in [A-Z$%] after an '~' with your substitution.

In the first case you have ~AK, so \w*[A-Z$%] evaluates to the 'AK', matching \w* -> A, and [A-Z$%] -> K

In the second case you cae ~$C so \w*[A-Z$%] evaluates to '$', matching \w* -> nothing, and [A-Z$%] -> $

I think the important thing is that \w is optional (zero or more), but the [A-Z$%] is mandatory. This is why the second case gives '$' not '$C' as the matched part.

Since I don't know what you're trying to achieve I cannot tell you how to fix your expression.

Richard