*! version 1.0.0 Matthew White 25nov2013

Title

specialexp -- Obtain expression that evaluates to string

Syntax

string scalar specialexp(string scalar s
[, real scalar n])

Description

specialexp() converts a string to an expression that
evaluates to the string.
It can facilitate writing do-files that use difficult strings.

Remarks

To be used in an expression, most strings need only be enclosed in
double quotes. However, strings that contain
the Stata special characters `, $, or " or
an ASCII control character, such as the line-feed character (\n),
may also need the \ escape character.
They may even require an expression that contains multiple strings.
For instance:

The string abc need only be enclosed in simple double quotes:

: specialexp("abc")

"abc"

The string `x' needs the \ escape character:

: s = "`" + "x" + "'"

: s

`x'

: specialexp(s)

"\`x'"

The string `\${x}""y""` requires more than the escape character;
it must be split into multiple strings:

: s = "`\" + `"\${x}""y"""' + "`"

: s

`\${x}""y""`

: specialexp(s)

"\`\" + `"\${x}""y"""' + "`"

: stata("mata: " + specialexp(s))

`\${x}""y""`

specialexp(s) returns an expression that evaluates to s.
specialexp(s, n) returns the expression and
stores in n the number of strings that the expression contains,
replacing n.

: specialexp("abc", n)

"abc"

: n

1

: s = "`\" + `"\${x}""y"""' + "`"

: s

`\${x}""y""`

: specialexp(s, n)

"\`\" + `"\${x}""y"""' + "`"

: n

3

Conformability

specialexp(s, n)

s: 1 x 1
n: 1 x 1
result: 1 x 1

Diagnostics

specialexp(s [, n]) aborts in error
if s contains binary 0 (\0).

Source code

specialexp.mata

Author

Matthew White, Innovations for Poverty Action

mwhite@poverty-action.org