简体   繁体   中英

Regexp for Visual Studio (2013+) to match and replace the exact same string

I'd like to search for expressions such as

..., "String", "String", ...

and replace that with say

..., "String", SAMESTRING, ...

So the main issue is how to make sure the 2nd string is the duplicate of the 1st string. Any ideas?

Here's a way to match and replace all repeated same strings:

using System;
using System.Text.RegularExpressions;

namespace myapp
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "\"a\", \"a\", \"b\", \"c\", \"c\", \"c\", \"d\"";
            string output = Regex.Replace(input, "(\"[^\"]*\")(?<=\\1, \\1)", "\"SAMESTRING\"");

            Console.WriteLine(output);        
        }
    }
}

Input: "a", "a", "b", "c", "c", "c", "d"

Output: "a", "SAMESTRING", "b", "c", "SAMESTRING", "SAMESTRING", "d"

It matches a string in double quotes, checks with a lookbehind if that string is preceded by the same string and a comma, and if yes, replaces the repeated string with "SAMESTRING".

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