tags:

views:

120

answers:

4

I have a little problem on RegEx pattern in c#. Here's the rule below:

input: 1234567 expected output: 123/1234567

Rules:

  1. Get the first three digit in the input. //123
  2. Add /
  3. Append the the original input. //123/1234567
  4. The expected output should looks like this: 123/1234567

here's my regex pattern:

regex rx = new regex(@"((\w{1,3})(\w{1,7}))");

but the output is incorrect. 123/4567

+4  A: 

It's not clear why you need a RegEx for this. Why not just do:

string x = "1234567";
string result = x.Substring(0, 3) + "/" + x;
Eddie Sullivan
@Dav: what slashes?
John Saunders
Hi Eddie, Good day! I have a little problem on RegEx pattern in c#. Please take note it should be done using RegEx pattern only. I already resolved this using substring() but I need to convert it using RegEx because I'll put the RegEx pattern on my config file so that there will be no data manipulatin inside my code. I hope you get my point.Thank you.
kurt_jackson19
Almost +1, but it should be `x.Substring(0, 3) + "/" + x;`
Kobi
Good catch Kobi. I fixed it in the original.
Eddie Sullivan
+2  A: 

Use positive look-ahead assertions, as they don't 'consume' characters in the current input stream, while still capturing input into groups:

Regex rx = new Regex(@"(?'group1'?=\w{1,3})(?'group2'?=\w{1,7})");

group1 should be 123, group2 should be 1234567.

Sam
hi sam, thank you for the reply. But I use the Match function. Is this correct? here's my code: Regex re = null; Match match = null; string input = "1234567";re = new Regex(@"((\w{1,3})(\w{1,32}))");match = re.Match(input);How do i apply the code that you proposed? Thanks a lot sam.Regards,kurt
kurt_jackson19
use match.Groups[groupName] to get named groups (ie match.Groups["group1"] == "123" )
Sam
+4  A: 

I think this is what you're looking for:

string s = @"1234567";
s = Regex.Replace(s, @"(\w{3})(\w+)", @"$1/$1$2");

Instead of trying to match part of the string, then match the whole string, just match the whole thing in two capture groups and reuse the first one.

Alan Moore
Exactly Alan that's what i'm looking for. Thank you so much guys you help me alot. @sam,eddie : thank you guys..
kurt_jackson19
+3  A: 

Another option is:

string s = Regex.Replace("1234567", @"^\w{3}", "$&/$&"););

That would capture 123 and replace it to 123/123, leaving the tail of 4567.

  • ^\w{3} - Matches the first 3 characters.
  • $& - replace with the whole match.

You could also do @"^(\w{3})", "$1/$1" if you are more comfortable with it; it is better known.

Kobi
Note that this doesn't support spaces or odd characters. You can use `.{3}` for the first 3 characters or every kind.
Kobi
Thanks kobi, I would also try that one. - kurt
kurt_jackson19