| GOLF(2gg) | Development | GOLF(2gg) |
NAME¶
split-string - (strings)
PURPOSE¶
Split a string into pieces based on a delimiter.
SYNTAX¶
split-string <string> with <delimiter> to <result> [ count <count> ] split-string delete <result>
DESCRIPTION¶
split-string will find all instances of string <delimiter> in <string> and then split it into pieces delimited by string <delimiter>. The <result> can be used with read-split to obtain the pieces and with split-string to delete it (use "delete" clause with <result> to delete it).
If "count" clause is used, then the number of pieces is in <count>.
All pieces produced will be trimmed both on left and right. If a piece is double quoted, then double quotes are removed. For instance save this code in "ps.golf" in a separate directory:
%% /parse public
set-string clist = "a , b, \"c , d\" , e"
split-string clist with "," to res count tot
start-loop repeat tot use i
read-split i from res to item status st
if-true st not-equal GG_OKAY
break-loop
end-if
// Output each item
print-format " [%s]", item
end-loop %%
Create the application, build and run it:
sudo mgrg -i -u $(whoami) ps gg -q gg -r --req="/parse" --exec --silent-header
The output would be:
[a] [b] [c , d] [e]
split-string is useful for parsing CSV (Comma Separated Values) or any other kind of separated values, where separator can be any string of any length, for example if you're parsing an encoded URL-string, then "&" may be a separator, as in the example below.
EXAMPLES¶
The following will parse a string containing name/value pairs (such as "name=value") separated by string "&":
%% /parse-url public
// Data to parse - data/value pairs delimited by "&" string, and data and value delimited by equal sign:
set-string url ="x=23&y=good&z=hello_world"
// Split string first into pieces based on "amp;"
split-string url with "&" to url_var count tot
// For each of name=value pairs, split it with equal sign
start-loop repeat tot use i
// Get a url pair (each separated with "&")
read-split i from url_var to item
// Then split that with "="
split-string item with "=" to item_var
// Get name and value
read-split 1 from item_var to name
read-split 2 from item_var to val
print-format "Variable %s has value %s\n", name, val
end-loop %%
The result is:
Variable x has value 23 Variable y has value good Variable z has value hello_world
SEE ALSO¶
Strings
concatenate-strings copy-string count-substring delete-string lower-string new-string read-split replace-string set-string split-string string-length trim-string upper-string write-string See all documentation
| $VERSION | $DATE |