Neobook Tip: Parsing Fields From Strings: getFields subroutine
Contributed by Sam Cox:
In my work I deal with 27-digit serial numbers consisting of a number of fixed-length, non-delimited fields. Wanting to break such serial number strings into their several fields, I wrote this general purpose field extraction subroutine:
SUBROUTINE CODE :
:getFields
strparse "[getFieldPos]" "," "[fieldPos]" "[fieldPosCount]"
strparse "[getFieldName]" "," "[fieldName]" "[fieldNameCount]"
if "[fieldPosCount]" "<>" "[fieldNameCount]"
alertbox "error" "fieldNameCount ([fieldnamecount]) <> fieldPosCount ([fieldposcount])"
return
else
loop "1" "[fieldPosCount]" "[n]"
strparse "[fieldPos[n]]" "-" "[p]" "[unused]"
substr "[getFieldSource]" "[p1]" "[p2]-[p1]+1" "[[fieldName[n]]]"
endloop
endif
return
I might use it like this:
setvar "[sn]" "E70886680744110520041400031"
gosub "snParse"
.returns useful results in [sn.pn][sn.edc][sn.sc][sn.dom][sn.yyyy][sn.ww][sn.seq]
where the :snParse subroutine defines the fields and variable names. Notice that for my purposes, I am extracting overlapping fields. Look at the definitions of the [sn.dom] and [sn.yyyy]+[sn.ww] fields.
:snParse
setvar "[getFieldSource]" "[sn]"
setvar "[getFieldPos]" "1-10,11-14,15-16,17-22,17-20,21-22,23-27"
setvar "[getFieldName]" "sn.pn,sn.edc,sn.sc,sn.dom,sn.yyyy,sn.ww,sn.seq"
gosub "getFields"
.
.additional work here to validate [sn]'s fields
.
return
Here's another version of 'getFields' without the error checking and with shorter interval variable names:
SUBROUTINE CODE:
:getFields
strparse "[getFieldPos]" "," "[:fp]" "[:fpc]"
strparse "[getFieldName]" "," "[:fn]" "[:unused]"
loop "1" "[:fpc]" "[:n]"
strparse "[:fp[:n]]" "-" "[
]" "[:unused]"
substr "[getFieldSource]" "[
1]" "[
2]-[
1]+1" "[[:fn[:n]]]"
endloop
return
