开发者

RegEx Problem using .NET

开发者 https://www.devze.com 2022-12-20 11:51 出处:网络
I have a little problem on RegEx pattern in c#. Here\'s the rule below: input: 1234567 expected output: 123/12345开发者_运维技巧67

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

input: 1234567 expected output: 123/12345开发者_运维技巧67

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


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.


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;


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消