亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字符串中每個字母后的換行符

字符串中每個字母后的換行符

C#
慕后森 2022-12-24 13:39:28
我有一個(水平)形式的字符串184.b189.a194.b199.d204.d209.b214.b219.d,我需要將其轉換為(垂直)形式184.b189.a194.b199.d.......我試圖Regex使用下面的正則表達式<br />找到每個字母表,這樣我就可以在字符串中的每個字母表后附加換行符。表達式工作正常,我不知道如何附加換行符 var count = Regex.Matches(text, @"[a-zA-Z]");
查看完整描述

2 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

您可以嘗試Regex.Replace:我們每個A..Za..z匹配項替換為自身,$0后跟一個新行

  string source = "184.b189.a194.b199.d204.d209.b214.b219.d";


  string result = Regex.Replace(source, "[A-Za-z]", $"$0{Environment.NewLine}");


  Console.Write(result); 

結果:


184.b

189.a

194.b

199.d

204.d

209.b

214.b

219.d

如果你想添加相同的想法<br />


  string result = Regex.Replace(source, "[A-Za-z]", $"$0<br />");

Linq是另一種選擇:


  string result = string.Concat(source

    .Select(c => c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' 

                   ? c.ToString() + "<br />" 

                   : c.ToString()));


查看完整回答
反對 回復 2022-12-24
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

您可以使用正則表達式(\d{3}\.[A-Za-z]) https://regex101.com/r/Z05cC4/1


這是:


\d{3} matches a digit (equal to [0-9])

{3} Quantifier — Matches exactly 3 times

\. matches the character . literally (case sensitive)

Match a single character present in the list below [A-Za-z]

A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)

a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)

然后只拿第一組。


public static class Program

{

    private static void Main(string[] args)

    {

        string input = @"184.b189.a194.b199.d204.d209.b214.b219.d";

        IEnumerable<string> capturedGroups = ExtractNumbers(input);


        string res = string.Join(Environment.NewLine, capturedGroups);

        Console.WriteLine(res);

    }


    static IEnumerable<string> ExtractNumbers(string Input)

    {

        string pattern = @"(\d{3}\.[A-Za-z])";

        MatchCollection matches = Regex.Matches(Input, pattern, RegexOptions.Singleline);


        foreach (Match match in matches)

            yield return match.Groups[1].Value;

    }

}

輸出:


184.b

189.a

194.b

199.d

204.d

209.b

214.b

219.d


查看完整回答
反對 回復 2022-12-24
  • 2 回答
  • 0 關注
  • 140 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號