简体   繁体   中英

C# regex repeating group of the digit in pattern

i use regex pattern

    pattern = "ID\\d+.*?ID\\d+";
    input="ID1...sometxt1...ID1...sometxt2...ID3...sometxt3...ID50"
    input=Regex.Replace(input, pattern, "");
    Console.WriteLine(input);

Output will = "...sometxt2..."
but i need Output
...sometxt2...ID3...sometxt3...ID50,

i need that regex find groups with equal digit after ID. ID3 != ID50, this group must remain, ID1==ID1 - this group must be replaced

Thank!

If you need to replace the whole substrings from ID having the same digits after them, you need to use a capturing group with a backreference:

var pattern = @"\bID(\d+).*?\bID\1\b";

See the regex demo

Explanation:

  • \\bID - a whole word "ID"
  • (\\d+) - one or more digits captured into Group 1
  • .*? - any characters but a newline, as few as possible up to the closest
  • \\bID - whole word "ID" followed with....
  • \\1 - backreference to the matched digits in Group 1
  • \\b - followed with a word boundary (so that we do not match 10 if we have 1 in Group 1).

Note that you will need RegexOptions.Singleline modifier if you have newline characters in your input strings.

Also, do not forget to assign the replacement result to a variable:

var res = Regex.Replace(input, pattern, string.Empty);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM