Remove text in-between delimiters in a string (usi

2020-01-24 12:09发布

Consider the requirement to find a matched pair of set of characters, and remove any characters between them, as well as those characters/delimiters.

Here are the sets of delimiters:

 []    square brackets
 ()    parentheses
 ""    double quotes
 ''    single quotes

Here are some examples of strings that should match:

 Given:                       Results In:
-------------------------------------------
 Hello "some" World           Hello World
 Give [Me Some] Purple        Give Purple
 Have Fifteen (Lunch Today)   Have Fifteen
 Have 'a good'day             Have day

And some examples of strings that should not match:

 Does Not Match:
------------------
 Hello "world
 Brown]co[w
 Cheese'factory

If the given string doesn't contain a matching set of delimiters, it isn't modified. The input string may have many matching pairs of delimiters. If a set of 2 delimiters are overlapping (i.e. he[llo "worl]d"), that'd be an edge case that we can ignore here.

The algorithm would look something like this:

string myInput = "Give [Me Some] Purple (And More) Elephants";
string pattern; //some pattern
string output = Regex.Replace(myInput, pattern, string.Empty);

Question: How would you achieve this with C#? I am leaning towards a regex.

Bonus: Are there easy ways of matching those start and end delimiters in constants or in a list of some kind? The solution I am looking for would be easy to change the delimiters in case the business analysts come up with new sets of delimiters.

5条回答
▲ chillily
2楼-- · 2020-01-24 12:14

I have to add the old adage, "You have a problem and you want to use regular expressions. Now you have two problems."

I've come up with a quick regex that will hopefully help you in the direction you are looking:

[.]*(\(|\[|\"|').*(\]|\)|\"|')[.]*

The parenthesis, brackets, double quotes are escaped while the single quote is able to be left alone.

To put the above expression into English, I'm allowing for any number of characters before and any number after, matching the expression in between matching delimiters.

The open delimiter phrase is (\(|\[|\"|') This has a matching closing phrase. To make this a bit more extensible in the future, you could remove the actual delimiters and contain them in a config file, database or wherever you may choose.

查看更多
一纸荒年 Trace。
3楼-- · 2020-01-24 12:18

Use the following Regex

(\{\S*\})

What this regex does is it replaces any occurences of {word} with the modifiedWord you want to replace it with.

Some sample c# code:

 static readonly Regex re = new Regex(@"(\{\S*\})", RegexOptions.Compiled);
        /// <summary>
        /// Pass text and collection of key/value pairs. The text placeholders will be substituted with the collection values.
        /// </summary>
        /// <param name="text">Text that containes placeholders such as {fullname}</param>
        /// <param name="fields">a collection of key values pairs. Pass <code>fullname</code> and the value <code>Sarah</code>. 
        /// DO NOT PASS keys with curly brackets <code>{}</code> in the collection.</param>
        /// <returns>Substituted Text</returns>
        public static string ReplaceMatch(this string text, StringDictionary fields)
        {
            return re.Replace(text, match => fields[match.Groups[1].Value]);
        }

In a sentence such as

Regex Hero is a real-time {online {Silverlight} Regular} Expression Tester.

It will replace only {Silverlight} and not starting from first { bracket to the last } bracket.

查看更多
别忘想泡老子
4楼-- · 2020-01-24 12:23

A simple way would be to do this:

string RemoveBetween(string s, char begin, char end)
{
    Regex regex = new Regex(string.Format("\\{0}.*?\\{1}", begin, end));
    return regex.Replace(s, string.Empty);
}

string s = "Give [Me Some] Purple (And More) \\Elephants/ and .hats^";
s = RemoveBetween(s, '(', ')');
s = RemoveBetween(s, '[', ']');
s = RemoveBetween(s, '\\', '/');
s = RemoveBetween(s, '.', '^');

Changing the return statement to the following will avoid duplicate empty spaces:

return new Regex(" +").Replace(regex.Replace(s, string.Empty), " ");

The final result for this would be:

"Give Purple and "

Disclamer: A single regex would probably faster than this.

查看更多
淡お忘
5楼-- · 2020-01-24 12:29

Building on Bryan Menard's regular expression, I made an extension method which will also work for nested replacements like "[Test 1 [[Test2] Test3]] Hello World":

    /// <summary>
    /// Method used to remove the characters betweeen certain letters in a string. 
    /// </summary>
    /// <param name="rawString"></param>
    /// <param name="enter"></param>
    /// <param name="exit"></param>
    /// <returns></returns>
    public static string RemoveFragmentsBetween(this string rawString, char enter, char exit) 
    {
        if (rawString.Contains(enter) && rawString.Contains(exit))
        {
            int substringStartIndex = rawString.IndexOf(enter) + 1;
            int substringLength = rawString.LastIndexOf(exit) - substringStartIndex;

            if (substringLength > 0 && substringStartIndex > 0)
            {
                string substring = rawString.Substring(substringStartIndex, substringLength).RemoveFragmentsBetween(enter, exit);
                if (substring.Length != substringLength) // This would mean that letters have been removed
                {
                    rawString = rawString.Remove(substringStartIndex, substringLength).Insert(substringStartIndex, substring).Trim();
                }
            }

            //Source: https://stackoverflow.com/a/1359521/3407324
            Regex regex = new Regex(String.Format("\\{0}.*?\\{1}", enter, exit));
            return new Regex(" +").Replace(regex.Replace(rawString, string.Empty), " ").Trim(); // Removing duplicate and tailing/leading spaces
        }
        else
        {
            return rawString;
        }
    }

Usage of this method would in the suggested case look like this:

string testString = "[Test 1 [[Test2] Test3]] Hello World";
testString.RemoveFragmentsBetween('[',']');

Returning the string "Hello World".

查看更多
姐就是有狂的资本
6楼-- · 2020-01-24 12:33

Simple regex would be:

string input = "Give [Me Some] Purple (And More) Elephants";
string regex = "(\\[.*\\])|(\".*\")|('.*')|(\\(.*\\))";
string output = Regex.Replace(input, regex, "");

As for doing it a custom way where you want to build up the regex you would just need to build up the parts:

('.*')  // example of the single quote check

Then have each individual regex part concatenated with an OR (the | in regex) as in my original example. Once you have your regex string built just run it once. The key is to get the regex into a single check because performing a many regex matches on one item and then iterating through a lot of items will probably see a significant decrease in performance.

In my first example that would take the place of the following line:

string input = "Give [Me Some] Purple (And More) Elephants";
string regex = "Your built up regex here";
string sOutput = Regex.Replace(input, regex, "");

I am sure someone will post a cool linq expression to build the regex based on an array of delimiter objects to match or something.

查看更多
登录 后发表回答