字符串中每个字母后的换行符

我有一个(水平)形式的字符串184.b189.a194.b199.d204.d209.b214.b219.d,我需要将其转换为(垂直)形式


184.b

189.a

194.b

199.d

.......

我试图Regex使用下面的正则表达式<br />找到每个字母表,这样我就可以在字符串中的每个字母表后附加换行符。表达式工作正常,我不知道如何附加换行符


 var count = Regex.Matches(text, @"[a-zA-Z]");


慕后森
浏览 119回答 2
2回答

暮色呼如

您可以尝试Regex.Replace:我们将每个A..Za..z匹配项替换为自身,$0后跟一个新行&nbsp; string source = "184.b189.a194.b199.d204.d209.b214.b219.d";&nbsp; string result = Regex.Replace(source, "[A-Za-z]", $"$0{Environment.NewLine}");&nbsp; Console.Write(result);&nbsp;结果:184.b189.a194.b199.d204.d209.b214.b219.d如果你想添加相同的想法<br />&nbsp; string result = Regex.Replace(source, "[A-Za-z]", $"$0<br />");Linq是另一种选择:&nbsp; string result = string.Concat(source&nbsp; &nbsp; .Select(c => c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;? c.ToString() + "<br />"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;: c.ToString()));

ibeautiful

您可以使用正则表达式(\d{3}\.[A-Za-z])&nbsp;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{&nbsp; &nbsp; private static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string input = @"184.b189.a194.b199.d204.d209.b214.b219.d";&nbsp; &nbsp; &nbsp; &nbsp; IEnumerable<string> capturedGroups = ExtractNumbers(input);&nbsp; &nbsp; &nbsp; &nbsp; string res = string.Join(Environment.NewLine, capturedGroups);&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(res);&nbsp; &nbsp; }&nbsp; &nbsp; static IEnumerable<string> ExtractNumbers(string Input)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; string pattern = @"(\d{3}\.[A-Za-z])";&nbsp; &nbsp; &nbsp; &nbsp; MatchCollection matches = Regex.Matches(Input, pattern, RegexOptions.Singleline);&nbsp; &nbsp; &nbsp; &nbsp; foreach (Match match in matches)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return match.Groups[1].Value;&nbsp; &nbsp; }}输出:184.b189.a194.b199.d204.d209.b214.b219.d
打开App,查看更多内容
随时随地看视频慕课网APP