3

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 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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;

3 Comments

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.
Almost +1, but it should be x.Substring(0, 3) + "/" + x;
Good catch Kobi. I fixed it in the original.
3

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.

2 Comments

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

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.

2 Comments

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
use match.Groups[groupName] to get named groups (ie match.Groups["group1"] == "123" )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.