RegEx problem using .NET

I have a little problem with RegEx pattern in C #. Here is the rule below:

input: 1234567 expected result: 123/1234567

Rules:

  • Get the first three digits of the input. // 123
  • Add /
  • Add original input. // 123/1234567
  • The expected result should look like this: 123/1234567

here is my regex pattern:

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

but the conclusion is wrong. 123/4567

+3
source share
4 answers

Another variant:

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

This will capture 123and replace it with 123/123, leaving the tail 4567.

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

You can also @"^(\w{3})", "$1/$1"if you prefer; it is better known.

+3

, RegEx. :

string x = "1234567";
string result = x.Substring(0, 3) + "/" + x;
+4

, , :

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

Instead of trying to match part of a line, match the entire line, just match it all in the two capture groups and reuse the first.

+4
source

Use positive statements ahead because they do not "consume" characters in the current input stream, while maintaining all the entries in the groups:

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

group1 must be 123, group2 must be 1234567.

+2
source

Source: https://habr.com/ru/post/1732946/


All Articles