我正在尝试使用正则表达式,我有以下字符串:
M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6
30470041106042700156
30470031201042506146
字符串模式为string pattern = @"\D";
,我想要打印:
M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6
因为它在此字符串中找到匹配项。我不打印30470041106042700156
30470031201042506146
,因为它找不到任何匹配项。
我写了代码:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"\D";
string input = @"M3A4S0S3I2M1O4 M3a4s0s3i2m1o4 m3a4s0s3i2m1o4 F3a4i0l4l1a6 30470041106042700156 30470031201042506146";
但我不知道怎么能完成它。我该如何解决?
答案 0 :(得分:2)
using System;
using System.Text.RegularExpressions;
public class Program {
public static void Main() {
string[] input = { "M3A4S0S3I2M1O4", "M3a4s0s3i2m1o4", "m3a4s0s3i2m1o4", "F3a4i0l4l1a6", "30470041106042700156", "30470031201042506146" };
foreach (var line in input)
if (Regex.IsMatch(line, @"\D"))
Console.WriteLine(line);
}
}
<强>输出强>
M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6
答案 1 :(得分:1)
实际上你不需要正则表达式,使用简单的拆分,连接和LINQ:
string input = @"M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6
30470041106042700156
30470031201042506146";
string res = string.Join("\r\n", input.Split(new[] {"\r\n"}, StringSplitOptions.None)
.Where(line => !line.All(Char.IsDigit))
.ToArray());
.Where(line => !line.All(Char.IsDigit))
部分仅保留非全数字的行。
如果您有一个字符串列表,请将string.Join("\r\n", input.Split(new[] {"\r\n"}, StringSplitOptions.None)
替换为您的列表变量并省略string.Join
。