ruby - Capture variable amount of matches with regular expressions? -


how if @ can use regex match string variable number of matches.

the strings want parse like:

'every 15th of month' 'every 21st , 28th of month' 'every 21st, 22nd , 28th of month' 

ad infinitum...

i want able capture ordinal numbers (15th, 21st etc)

the language i'm using ruby it's worth.

thanks, alex

you can capture them array scan, match occurrences of regex:

irb(main):001:0> s = 'every 15th of month' => "every 15th of month" irb(main):003:0> s2 = 'every 21st , 28th of month' => "every 21st , 28th of month" irb(main):004:0> s3 = 'every 21st, 22nd, , 28th of month' => "every 21st, 22nd, , 28th of month" irb(main):006:0> myarray = s3.scan(/(\d{1,2}(?:st|nd|rd|th))/) => [["21st"], ["22nd"], ["28th"]] irb(main):007:0> myarray = s2.scan(/(\d{1,2}(?:st|nd|rd|th))/) => [["21st"], ["28th"]] irb(main):008:0> myarray = s.scan(/(\d{1,2}(?:st|nd|rd|th))/) => [["15th"]] irb(main):009:0> 

then of course can access each match using typical myarray[index] notation (or loop through of them, etc).

edit: based on comments, how this:

ordinals = (1..31).map { |n| activesupport::inflector::ordinalize n }  day_of_month_regex = /(#{ordinals.join('|')})/i myarray = string.scan(day_of_month_regex) 

this gets tripped ordinal numbers might appear in other phrases. trying more restrictive pretty ugly, since have cover bunch of different cases. might able come something...but wouldn't worth it. if want parse string fine-grained control , variable amount of text match, isn't job regex, honest. it's hard without knowing format lines are, if coming file other similar lines, if have control on format/contents of strings, etc.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -