Regular expression to validate text

Asked

Viewed 301 times

2

I am making a method that will import some data, and before the import I need to check if some fields are correctly filled, the fields should come this way:

Example:

Jan/Seg
Fev/Ter
Mar/Qui

The data must be in this exact format, where the first 3 characters represent the prefix of the month, followed by a bar and after 3 characters representing the day of the week.

I need to check if the prefix of the month is valid and if the prefix of the week too, and it needs to contain both, I thought to make a regex that does this, but I do not know how to do in C#, Does anyone know a good way to do that? Thank you very much.

  • 2

    How’s the data coming? Valid data are only those whose lines have 7 characters, the first 3 being the prefix of the month, the fourth the bar and the last 3 characters the prefix of the day of the week?

  • Exact, the data will come from an excel spreadsheet and need to be in this exact format, I will add in question this information.

1 answer

3


I don’t know how it’s done in C#, but Regular Expression could be like this:

^(Jan|Fev|Mar|Abr|Mai|Jun|Jul|Aug|Set|Out|Nov|Dez)\/(Seg|Ter|Qua|Qui|Sex|Sab|Dom)$

that she can validate for you

  • 3

    It may be silly of me, but I think putting the boundaries ^ and $ would ensure that the line contains just that. See the update in question, the line needs to be exactly that.

  • Yes I agree, I would be more specific

  • 1

    So I took the liberty of doing it

  • 2

    You can reduce some things: March and May can be condensed with Ma[ri] (Ma followed by r or i). Likewise, July and July may be Ju[ln] and Fourth and Fifth, Qu[ai], and Monday and Friday, Se[gx], see here. But your regex tb is right :-) And use ^ and $ not only to leave "more specific", in this case it is ideal since the lines should have only this content, and not using them would cause false positives (the line could have other characters before or after and would be considered valid).

  • 2

    @hkotsubo I still think regex is unnecessary for this case :) I think string checking can be simpler and faster

  • 1

    @Jeffersonquesado I agree, regex is not always the best solution for everything :-)

Show 1 more comment

Browser other questions tagged

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