decorative banner

Previous | Next               Table Of Contents > 2 Working with string and numeric variables > 2.5 Modifying string contents

2.5 Modifying string contents


The strslice command can be used to extract part of a string. The left and right keywords are used to specify the start direction for the extracted string slice. The offset specifies the number of characters to skip from the start direction. The character count specifies the number of characters to extract. A value of 0 for the character count extracts the entire remaining portion of the string. The extracted string replaces the original string contained in the variable.

The syntax is

strslice <variable>, <keyword: left, right>, <offset from start direction>, <character count>;

Some examples are

setvar ~my_var, "my_string_value";

strslice ~my_var, left, 4, 0; #start from left, skip 4 chars and extract rest of the string. ~my_var contains "tring_value"

strslice ~my_var, left, 0, 4; #start from left, extract 4 chars. ~my_var contains "my_s"

strslice ~my_var, right, 4, 0; #start from right, skip 4 chars and extract rest of the string. ~my_var contains "my_string_v"

strslice ~my_var, right, 0, 5; #start from right, extract 5 chars. ~my_var contains "value"

       

The regexreplace command replaces parts of a string with another string based on a regular expression pattern. This is similar to the substitution operation in Perl. The regex pattern specifies the regular expression pattern to search for in the original string. The replacement text specifies the string to substitute when a match is found. The match options specify other conditions that affect a match. The available match options are:

i    perform a case insensitive match
g    match all occurances of a pattern

Note that for the regular expression pattern string, a \ character must be preceeded by another \.

The syntax is

regexreplace <variable>, <regex pattern string>, <replacement text string>, <match options>;

Some examples are

setvar ~my_var, "xyz_file_050502out.txt";

regexreplace ~my_var, "[0-9]+", "", "ig"; #remove all numbers in string. ~my_var contains "xyz_file_out.txt"

regexreplace ~my_var, "[0-9]+", "00000", "ig"; #replace numbers in string with 00000. ~my_var contains "xyz_file_00000out.txt"

The replacement text can also contain backreferences. Backreferences are specified using $1 for the subexpression matched in the first parenthesis, $2 for the subexpression matched in the second parenthesis and so on.

Some examples are

setvar ~my_var, "dat_file.txt";

regexreplace ~my_var, "([_a-zA-Z0-9]+)\\.[_a-zA-Z0-9]+", "$1.log", "ig"; #rename extension from txt to log. ~my_var contains "dat_file.log";

regexreplace ~my_var, "([_0-9a-zA-Z]+)[.][_0-9a-zA-Z]+", "$1_050402.txt", "ig"; #append a timestamp. ~my_var contains "dat_file_050402.txt


Previous | Next