TioTorres
TioTorres

Reputation: 13

Match days, months and years on string

I would like to match days, months and years in three different groups, so I would know that group[0] = years, group[1] = months, group[2] = days.

Ano == Year, Anos == Years<br>
Mes == Month, Meses == Months<br>
Dia == Day, Dias == Days<br><br>

Input:

   1 ano 12 meses 1 dia
    2 anos
    1 ano
    1 mes
    1 dia
    2 meses 1 dia
    1 mes 3 dias
    3 dias

Here's the pattern that I've tried:
([0-9]+)ano*([0-9]+)mes*([0-9]+)dia

Output needed:

    1 12 1 
    2 
    1 
    1 
    1 
    2 1 
    1 3 
    3 


Live Example:

Upvotes: 0

Views: 223

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below regex,

(?:(\d+)\s*ano\S*)?(?:\s*(\d+)\s*mes\S*)?(?:\s*(\d+)\s*dia\S*)?

DEMO

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80639

(?:(\d+) anos?)?(?:(?:^| )(\d+) mes(?:es)?)?(?:(?:^| )(\d+) dias?)?

The above pattern will work. You'd need to use the multiline flag (m) as well.

Here's an example: http://regex101.com/r/wA6xJ2/1

Upvotes: 1

Related Questions