【问题标题】:Easy formatting of a string instead of using repetitive "Replace"Easy formatting of a string instead of using repetitive \"Replace\"
【发布时间】:2022-12-01 18:37:04
【问题描述】:

Is there a shortcut in replacing characters in a string? My string is like this:

string x = "[\r\n  \"TEST\",\r\n  \"GREAT\"\r\n]";

I want to have an output of only

TEST,GREAT

Right now I'm formatting it like: x..Replace("\r\n", "").Replace("[", "") and until I put all the characters.

My question is there a shortcut to do that instead of many "Replace"? It does not matter if it will be a string or put in a List of string. As long as I have the result TEST,GREAT.

【问题讨论】:

标签: c# arrays string string-formatting


【解决方案1】:

It looks like you want to remove the substrings, not replace them. You can use this extension method:

public static class RemoveExtensions
{
    public static string RemoveMultiple(this string str, params string[] removes)
    {
        foreach (string s in removes)
        {
            str = str.Replace(s, "");
        }
        return str;
    }
}

Use it like this:

string x = "[
  "TEST",
  "GREAT"
]";
string result = x.RemoveMultiple("
", "[", "]");

【讨论】:

    【解决方案2】:

    First of all, create a helper method to hide this:

    public static string ExtractLetters(this string text) // it's an extension method
    {
        return text.Replace("
    ", "").Replace("[", "")....;
    }
    

    now you can use it like this:

    var extracted = "[ "TEST", "GREAT" ]".ExtractLetters()

    already a bit better.

    Since I think your goal isn't really to replace things, just etract what you want, you can use regex:

    using System.Text.RegularExpressions;
    
    public static string ExtractLetters(this string text)
    {
        var regex = new Regex("[a-zA-Z]+"); // define regex, look for regex compilation and instance caching for optimizations here
        string[] matches = regex.Matches(text).Select(x => x.Value).ToArray(); // extract matches
            
        return string.Join(",", matches); // join them if you want
    }
    

    To develop the regex, use a website like https://regex101.com/

    【讨论】:

      猜你喜欢
      • 2022-12-27
      • 2022-12-27
      • 2022-12-27
      • 2022-12-02
      • 2019-09-10
      • 2013-09-30
      • 2011-05-16
      • 2022-12-04
      • 2023-02-09
      相关资源
      最近更新 更多