簡體   English   中英

輕松格式化字符串而不是使用重復的“替換”

[英]Easy formatting of a string instead of using repetitive "Replace"

是否有替換字符串中字符的快捷方式? 我的字符串是這樣的:

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

我只想擁有一個 output

TEST,GREAT

現在我將其格式化為:x..Replace("\r\n", "").Replace("[", "") 直到我輸入所有字符。

我的問題是有沒有捷徑可以代替許多“替換”? 不管它是一個字符串還是放在一個字符串列表中都沒有關系。 只要我有結果 TEST,GREAT。

這看起來像格式化 JSON。所以你可以這樣對待它!

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

    // Parse JSON to a list (could be anything implementing IEnumerable<>) of strings
    var words= System.Text.Json.JsonSerializer.Deserialize<List<string>>(x);

    // And join the values back together with a comma
    var result = string.Join(',', words);

    Console.WriteLine(result);

看起來您想刪除子字符串,而不是替換它們。 您可以使用此擴展方法:

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

像這樣使用它:

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

首先,創建一個輔助方法來隱藏它:

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

現在你可以像這樣使用它:

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

已經好一點了。

因為我認為你的目標不是真正地替換東西,只是提取你想要的東西,你可以使用正則表達式:

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
}

要開發正則表達式,請使用像https://regex101.com/這樣的網站

暫無
暫無

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

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