How to find certain words inside a string in C#

Asked

Viewed 93 times

0

For example:

string query = "INSERT INTO Recibos (idRecibo, DataRecibo, NomeCliente, Valor, CPFCliente, EnderecoCliente, NumeroCliente, BairroCliente, Importancia, Referente, Cidade, UF, Emitente, EnderecoEmitente, NumeroEmitente, BairroEmitente, CPFEmitente, RG) VALUES (" +
                        "@idRecibo," +
                        "@dataRecibo," +
                        "@nomeCliente," +
                        "@valor," +
                        "@cpfCliente," +
                        "@endCliente," +
                        "@numCliente," +
                        "@baiCliente," +
                        "@importancia," +
                        "@referente, +" +
                        "@cidade," +
                        "@uf," +
                        "@emitente," +
                        "@endEmitente," +
                        "@numEmitente," +
                        "@baiEmitente," +
                        "@cpfEmitente," +
                        "@rg)";

I would like to make a method that can scan the entire string and return to me all the words that are preceded by the @ symbol (with it included).

  • The word Simbolo missed accent. And I edited and let the most beautiful code preview.

3 answers

2


From the comment you made in @Catarina Batista’s reply, I understood that you would like to create a custom method to search all the parameters of your query and then customize it your way.

I made a method based on your description, but I can’t tell you if it’s done right.

public static List<string> ReturnAllParameters(string query)
{
    var parameterName = new StringBuilder();
    var parameters = new List<string>();

    for (int i = 0; i < query.Length; i++)
    {
        if (query[i] == '@')
        {
            do
            {
                parameterName.Append(query[i]);
                i++;
            } while (char.IsLetterOrDigit(query[i]));

            parameters.Add(parameterName.ToString());
            parameterName.Clear();
        }
    }

    return parameters;
}

Then call the method and you will get a list of string with all parameters of your query.

var parameters = ReturnAllParameters(query);
  • That’s right. What I really wanted was a (custom) method for sweeping everything I wanted. I believe the method you have made will help me with that. Thank you very much for the feedback and the method.

  • Glad I could help you! If the answer really was helpful to you and helped you solve your problem, could you mark it as an accepted answer to help others recognize that it is useful? Thank you.

  • It worked perfectly. Thank you.

1

Friend, I believe that if performance is a concern of yours, it would be more interesting - and succinct - to use a Regex for this search.

The @Pedro Paulo response is interesting, but it uses several processes that can be optimized with the use of Regex.

    static List<string> BuscarPalavras(string consulta, string regex = @"(?<!\w)@\w+")
    {
        var resultado = new List<string>(); 
        foreach (Match match in Regex.Matches(consulta, regex))
            resultado.Add(match.Value);

        return resultado;
    }

Each if and for removed are less complexity in the application. This way the function has two entries, its query and the regex standard that already comes with default value becoming an optional parameter, but that can be modified to search for other types of words. And an output value only, in case the word list.

If you have difficulty with Regex, you can play the value that is in the code on Regex101 that he’ll explain to you what he’s doing in more detail, and you can even modify it.

  • 1

    Actually regex is expensive, because internally it has to maintain several internal structures to function (maybe in this case, the performance is even worse than "the if and the for", but just testing to know - although for small strings should not make much difference). In your case, you still used lookbehind, which makes it even more costly... See the number of steps taken - maybe we can simplify to "@\w+, that improves a little - see how the number of steps decreases

  • 1

    It is true that with regex the code is more "succinct", but this does not necessarily mean that it is more efficient. Regex engine is a complex business, just see the source code the most widely used engine (in which most languages mainstream are based) to see that in fact you just delegated the complexity to an API. But nothing guarantees that the performance will be better. Don’t get me wrong, I like regex a lot, but to say that the performance will improve is a mistake, can only be sure to test a lot...

  • No offense taken! In my vision using regex seemed more interesting, but of course, it needs testing! I’m still learning to use it right, so these details made the lookbehind pass me unnoticed. But thanks for the touch!

  • Yes, regex is a very complex subject and the more I study, the more I realize I know nothing... But broadly speaking, the normal of regex is to go forward in the string, and only come back when needed. But when using lookbehind, you force it to come back all the time, since the idea of lookbehind is precisely to check what it has before the current position. So it takes longer, and in this particular case I guess I wouldn’t even have to use...

  • I want to thank everyone for the explanations and the method created. I will test the methods created by you to verify which the fastest and which best meets my needs.

  • The method worked very well. Thank you very much.

Show 1 more comment

0

I was a little confused about your question, but if you are referring to replacing these parameters with variables it is, (with mysql):

static public MySqlCommand Command { get; set; }


Command.Parameters.AddWithValue("@idRecibo", nomeVariavel);
  • Thanks for the answer. But I already use "Command.Parameters.Addwithvalue("@idRecibo", variablename);". I would like to create the method to be used in other situations.

Browser other questions tagged

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