Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Regular Expression: print strings different from the pattern

Tags:

c#

regex

I'm trying using Regular Expression and I have the following string:

M3A4S0S3I2M1O4
M3a4s0s3i2m1o4   
m3a4s0s3i2m1o4
F3a4i0l4l1a6
30470041106042700156
30470031201042506146

The string pattern is string pattern = @"\D"; and I want to print:

M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6

Because it finds matches in this string. I don't print 30470041106042700156 30470031201042506146 because it doesn't find any matches. I write the code:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\D";
        string input = @"M3A4S0S3I2M1O4 M3a4s0s3i2m1o4 m3a4s0s3i2m1o4    F3a4i0l4l1a6 30470041106042700156 30470031201042506146";

But I don't know how can I finish it. How can I fix?

like image 549
FabioBit Avatar asked Apr 19 '26 17:04

FabioBit


2 Answers

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

Output

M3A4S0S3I2M1O4
M3a4s0s3i2m1o4
m3a4s0s3i2m1o4
F3a4i0l4l1a6
like image 172
Shreevardhan Avatar answered Apr 21 '26 08:04

Shreevardhan


You do not need a regex here actually, use a simple split, join and 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());

The .Where(line => !line.All(Char.IsDigit)) part only keeps the lines that are not all-digits.

If you have a list of strings, replace string.Join("\r\n", input.Split(new[] {"\r\n"}, StringSplitOptions.None) with your list variable and omit string.Join.

enter image description here

like image 28
Wiktor Stribiżew Avatar answered Apr 21 '26 08:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!