我有一个184.b189.a194.b199.d204.d209.b214.b219.d
(水平)形式的字符串,我需要将其转换为(垂直)形式
184.b
189.a
194.b
199.d
.......
我尝试Regex
使用下面的 regex表达式查找每个字母,因此我可以在字符串中的每个字母之后附加换行符<br />
。表达式工作正常,我不知道如何追加换行符
var count = Regex.Matches(text, @"[a-zA-Z]");
答案 0 :(得分:0)
您可以尝试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()));
答案 1 :(得分:0)
您可以使用正则表达式(\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