How to directly compare strings treated with Regex in C# directly

Asked

Viewed 152 times

1

Hello, I come from the web (javascript) and I have the habit of working with OO mixing a little functional paradigm. Imagine the following situation.

  • I have a CC I have to check if it exists in the database;
  • I have no control over the formatting, so I do a treatment to remove your mask and check what’s left;
  • From that, I access a DbContext using Entityframework, and checking, based on the result of a Regex whether or not CPF exists in the database.

Normally on the web I would do something like:

var list = [ ... ]; // aqui seria um mockup do banco de cpf's ou o retorno
                    // de um webservice, etc...

var cpf = '000.000.000-00';

function exists(cpf, list) {
    var rx = /[-/.]/g;
    return list.filter(x => x.replace(rx,'') === cpf.replace(rx,'')).length > 0;
}

console.log(exists(cpf, list));

But when trying to do something similar in C# I am having a message that I cannot compare the result of 2 regex directly. My code is as follows:

// classe DbContext
public class Db: DbContext 
{
    public virtual DbSet<Pessoa> Pessoa { get; set; }
}

// classe Model (de acesso ao banco de dados)
public class Pessoa 
{
    // propriedades (reduzidas para brevidade)
    public string Cpf { get; set; }

    // método de consulta
    public bool exists(string cpf)
    {
        using (var db = new Db())
        {
            var rx = new Regex("[-/.]+");
            return db.Pessoa.Where(x => rx.Replace(x.Cpf).Equals(rx.replace(cpf,""))).First() != null;
        }
    }
}

Cannot make comparisons with regex in c# or the shape I made is unclear?

  • 1

    I’ve had problems like that using expressions on Where, maybe ride different solves, something like var pessoa = (from p in db.Pessoa where rx.Replace(x.Cpf).Equals(rx.replace(cpf,"")) select p).First()

  • 1

    regex to check if there is ? if you have already cleaned the string, just check... db.Pessoa.Any(x => x.Cpf == _cpf)

  • @Rovannlinhalis the idea is exactly do not clean out, but take advantage of it inside the Linq... even so I will try with the .Any

1 answer

2


You can compare 2 regex yes, maybe the problem is that your second Replace is with the r minuscule.

If you just want to check if it exists, use the .Any instead of .Where:

// método de consulta
public bool exists(string cpf)
{
    using (var db = new Db())
    {
        var rx = new Regex("[-/.]+");
        return db.Pessoa.Any(x => rx.Replace(x.Cpf).Equals(rx.Replace(cpf,"")));
    }
}

I also recommend not using regex for this kind of simple thing:

private RemoveCpfFormat(string formatedCpf) => formated.Replace(".", "").Replace("-", "");

I don’t know if you are the one who inserts in this database, but I also recommend maintaining a formatting pattern when inserting.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.