Re: How to convert sequence of characters to numbers
- Posted by ghaberek (admin) Oct 19, 2012
- 1510 views
casey said...
I need to convert a date/time string (sequence) of the format "20121018123010" into a sequence of numeric values of the format {2012,10,18,12,30,10} I'm looking for the fastest routine execution time possible. It looks like I could use breakup() and then maybe to_integer() or value() on each of the six elements. Am I missing something or is there a better way. Ultimately I need to poke2 each of the word values into a c_func call
Obligatory XKCD reference: Regular Expressions
include "std/convert.e" include "std/regex.e" regex pattern = regex:new( "([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})" ) function get_parts( sequence string ) sequence parts = {} if regex:is_match( pattern, string ) then object matches = regex:matches( pattern, string ) parts = repeat( 0, length(matches)-1 ) for i = 1 to length(matches)-1 do parts[i] = to_integer( matches[i+1] ) end for end if return parts end function
Example:
sequence string = "20121018123010" sequence parts = get_parts( string ) printf( 1, "string = \"%s\"\n", {string} ) puts( 1, "parts = " ) ? parts
Output:
$ eui regex-test.ex string = "20121018123010" parts = {2012,10,18,12,30,10}
-Greg