How to make a direct comparison between strings handled with RegEx in C # directly

1

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

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

Usually 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'm having a message that I can not 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;
        }
    }
}

Can not make comparisons with regex in C # or the way I did is not clear?

    
asked by anonymous 23.07.2018 / 16:14

1 answer

2

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

If you just want to check if it exists, use .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 to use regex for this simpler type of thing:

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

I do not know if you are the one inserting into this database, but I also recommend keeping a formatting pattern when inserting.

    
23.07.2018 / 17:35