preg_match(...) for various text types

Asked

Viewed 535 times

3

How can I validate the texts below?

Letters (including accents) and numbers (without spacing), separated by . or . e.g. 'olá123'

Integers and/or decimals. ex: '22' or '2.2'

  • summarizing: letters that contain numbers and numbers in general even the fractions. That’s it?

  • That’s right. But both without spaces. Fractional numbers with , or .

  • 3

    accepts coffee, tea, water?

2 answers

4

In a another question have a reply that can be of help.

In your case it is a little vague, because you do not specify if the numerals can come before, then be in the middle, if it can be mixed.

~^(?=.*[[:alpha:]].*)([[:alpha:]]*(\d+([.,]\d+)?)?[[:alpha:]]*)*$~u

This REGEX will accept all the questions I posed above.

  • 123test
  • test123
  • test123test
  • 123teste123
  • t3st3

Explanation

  • ([[:alpha:]]*(\d+([.,]\d+)?)?[[:alpha:]]*)* - This part frees to have letters before after the digits, but note that all of them are optional, which would release the NADA.
  • (?=.*[[:alpha:]].*) - This party shall ensure that string has at least one alpha.

As I had already commented in another reply.

  • [:alpha:] = [a-zA-Z], but note that there is a difference, as I will use the modifier u Unicode, the ideal is to use the [:alpha:] as it will also include accented characters.

2

Nothing that a good studied on regular expressions don’t solve.

Only the part of the accents that doesn’t include, but the rest is ok.

[a-zA-Z]+(\d+((\.|,)\d+)?)

[a-za-Z]+

Box with letters from a to z or from A to Z with 1 or more occurrences.

(\d+

Box with 1 or more numeric digits and starts a group.

(.|,)

After the digits must have a .(dot) or a ,(comma), the parentheses are to group an excerpt.

\d+

After the point or comma, plus a sequence of digits

)?)

Closes the 2 groups that were opened before, being the most internal optional.

It’s kind of complicated to describe regex by text, I find it particularly hard to understand, especially at the beginning.

This site regexpal serves to test the regex, makes life much easier.

  • Good answer, but this does not work with accents, I recommend you review ;)

Browser other questions tagged

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