tags:

views:

51

answers:

1

Is there a simple way to move percentage pointer after the value:

120 @ %60 {a} >> 120 @ 60% {a}
+2  A: 

Try this:

string input = "120 @ %60 {a}";
string pattern = @"%(\d+)";
string result = Regex.Replace(input, pattern, "$1%");
Console.WriteLine(result);

The %(\d+) pattern matches a % symbol followed by at least one digit. The digits are captured in a group which is referenced via the $1 in the replacement pattern $1%, which ends up placing the % symbol after the captured number.

If you need to account for numbers with decimal places, such as %60.50, you can use this pattern instead: @"%(\d+(?:\.\d+)?)"

Ahmad Mageed
I need to learn these regular expressions well :). Thanks.For opposite I've used: result = Regex.Replace(result, @"(\d+)%", "%$1");
HasanGursoy
@Ahmad Mageed: Also the value could contain 3.5 so I've replaced d with f Regex.Replace(result, @"(\f+)%", "%$1"); tell me if I'm wrong.
HasanGursoy
@Hasan that is incorrect since `\d` represents digits `[0-9]` whereas `f` isn't a special regex metacharacter for anything. To match numbers that contain a decimal point (ie. 3.5, 60.50 etc.) use the pattern I provided in my answer: `@"%(\d+(?:\.\d+)?)"`. This matches both numbers with and without decimal points. Next, the opposite would be the pattern `@"(\d+(?:\.\d+)?)%"`. The `(?:\.\d+)?` part matches a decimal point (an escaped dot `\.`) followed by numbers again (`\d+`). It's enclosed in `(?:...)?` which means *optionally* match it but don't capture it. The final `?` makes it optional.
Ahmad Mageed
Also take a look at http://msdn.microsoft.com/en-us/library/az24scfc%28VS.71%29.aspx for available regex elements. Specifically, look under "Character Classes" and you'll see `\d` but not `\f`. `f` actually exists under "Character Escapes" (a different section) and represents a form feed. However, that is not what you want for this problem. Hope that helps :)
Ahmad Mageed
@Ahmad Mageed: Oh it was just a guess. But unexpectedly it worked as needed :). Thanks anyway. I'll use your solution. Please tell me how did you learn all this regex stuff :D
HasanGursoy