簡體   English   中英

刪除字符串中的分隔符之間的文本(使用正則表達式?)

[英]Remove text in-between delimiters in a string (using a regex?)

考慮要求找到一對匹配的字符集,並刪除它們之間的任何字符, 以及那些字符/分隔符。

以下是分隔符集:

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

以下是一些應匹配的字符串示例:

 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

以及一些不匹配的字符串示例:

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

如果給定的字符串不包含匹配的分隔符集,則不會對其進行修改。 輸入字符串可以具有許多匹配的分隔符對。 如果一組2個分隔符重疊(即he[llo "worl]d" ),那就是我們可以忽略的邊緣情況。

該算法看起來像這樣:

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

問題:如何使用C#實現這一目標? 我傾向於正則表達式。

額外:是否有簡單的方法可以在常量或某種列表中匹配這些起始和結束分隔符? 我正在尋找的解決方案很容易更改分隔符,以防業務分析師提出新的分隔符集。

簡單的正則表達式將是:

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

至於你想要構建正則表達式的自定義方式,你只需要構建部分:

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

然后將每個單獨的正則表達式部分與OR(正則表達式中的|)連接,如我原始示例中所示。 一旦你建立了正則表達式字符串,就運行一次。 關鍵是要將正則表達式放入單個檢查中,因為在一個項目上執行許多正則表達式匹配然后迭代很多項目可能會看到性能顯着下降。

在我的第一個例子中,它將取代以下行:

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

我相信有人會發布一個很酷的linq表達式來構建正則表達式,基於一組分隔符對象來匹配或者什么。

一個簡單的方法是這樣做:

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, '.', '^');

將return語句更改為以下內容將避免重復的空格:

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

最終結果將是:

"Give Purple and "

免責聲明 :單個正則表達式可能比這更快。

我必須添加一句古老的格言,“你有一個問題,你想使用正則表達式。現在你有兩個問題。”

我想出了一個快速的正則表達式,希望能幫助你朝着你正在尋找的方向前進:

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

括號,括號,雙引號被轉義,而單引號可以單獨存在。

要將上面的表達式放到英語中,我允許之前的任意數量的字符和之后的任何數字,匹配匹配分隔符之間的表達式。

開放分隔符短語是(\\(|\\[|\\"|')這有一個匹配的結束短語。為了使將來更具可擴展性,你可以刪除實際的分隔符並將它們包含在配置文件,數據庫中或者你可以選擇的任何地方。

Bryan Menard的正則表達式的基礎上 ,我做了一個擴展方法,它也適用於嵌套替換,如“[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;
        }
    }

在建議的情況下,此方法的用法如下所示:

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

返回字符串“Hello World”。

使用以下正則表達式

(\{\S*\})

這個正則表達式的作用是將{word}的任何出現替換為要替換它的modifiedWord。

一些示例c#代碼:

 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]);
        }

在諸如此類的句子中

Regex Hero是一個實時{online { Silverlight } Regular} Expression Tester。

它將僅替換{ Silverlight }而不是從第一個{bracket到最后}括號開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM