String expressions (GNU Coreutils 9.0)
16.4.1 String expressions
expr supports pattern matching and other string operators. These have higher precedence than both the numeric and relational operators (in the next sections).
string : regex’
Perform pattern matching. The arguments are converted to strings and the second is considered to be a (basic, a la GNU
grep) regular expression, with a
^implicitly prepended. The first argument is then matched against this regular expression.
regexdoes not use ‘
\(’ and ‘
:expression returns the number of characters matched, or 0 if the match fails.
\(’ and ‘
:expression returns the part of
stringthat matched the subexpression, or the null string if the match failed or the subexpression did not contribute to the match.
Only the first ‘
\( … \)’ pair is relevant to the return value; additional pairs are meaningful only for grouping the regular expression operators.
In the regular expression,
\|are operators which respectively match one or more, zero or one, or separate alternatives. These operators are GNU extensions. See Regular Expressions in The GNU Grep Manual, for details of regular expression syntax. Some examples are in Examples of expr.
match string regex’
An alternative way to do pattern matching. This is the same as ‘
string : regex’ /@w .
substr string position length’
Returns the substring of
positionwith length at most
length. If either
lengthis negative, zero, or non-numeric, returns the null string.
index string charset’
Returns the first position in
stringwhere the first character in
charsetwas found. If no character in
charsetis found in
string, return 0.
Returns the length of
tokenas a string, even if it is a keyword like
matchor an operator like
/. This makes it possible to test
expr length + "$x"or
expr + "$x" : '.*/\(.\)'and have it do the right thing even if the value of
$xhappens to be (for example)
index. This operator is a GNU extension. Portable shell scripts should use
" $token" : ' \(.*\)'instead of
expr interpret keywords as strings, you must use the