Skip to main content

Returning a Substring

Returning a Substring

$WEXTRACT returns a substring by character position from string. The nature of this substring extraction depends on the arguments used:

  • $WEXTRACT(string) extracts the first character in the string.

  • $WEXTRACT(string,from) extracts a single character in the position specified by from. The from value can be an integer count of characters from the beginning of the string, an asterisk specifying the last character of the string, or an asterisk with a negative integer specifying a character count backwards from the end of the string.

    The following example extracts single letters from a string containing a surrogate pair. Note that $LENGTH counts a surrogate pair as two characters, but $WEXTRACT counts a surrogate pair as a single character:

      SET hipart=$CHAR($ZHEX("D806"))
      SET lopart=$CHAR($ZHEX("DC06"))
      SET spair=hipart_lopart /* surrogate pair */
      WRITE "length of surrogate pair ",$LENGTH(spair),!
      SET mystr="AB"_spair_"DEFG"
      WRITE !,$WEXTRACT(mystr,4)    // "D" the 4th character
      WRITE !,$WEXTRACT(mystr,*)    // "G" the last character
      WRITE !,$WEXTRACT(mystr,*-5)  // "B" the offset 5 character from end
      WRITE !,$WEXTRACT(mystr,*-0)  // "G" the last character by 0 offset
  • $WEXTRACT(string,from,to) extracts the range of characters starting with the from position and ending with the to position (inclusive). The following $WEXTRACT functions both return the string “Alabama”, counting surrogate pairs as single characters:

      SET hipart=$CHAR($ZHEX("D806"))
      SET lopart=$CHAR($ZHEX("DC06"))
      SET spair=hipart_lopart /* surrogate pair */
      SET var2=spair_"XXX"_spair_"Alabama"_spair
       WRITE !,$WEXTRACT(var2,6,12)
       WRITE !,$WEXTRACT(var2,*-7,*-1)

    If the from and to positions are the same,$WEXTRACT returns a single character. If the to position is closer to the beginning of the string than the from position, $WEXTRACT returns the null string.

FeedbackOpens in a new tab