Julia Language String Macros Using string macros


Example

String macros are syntactic sugar for certain macro invocations. The parser expands syntax like

mymacro"my string"

into

@mymacro_str "my string"

which then, like any other macro call, gets substituted with whatever expression the @mymacro_str macro returns. Base Julia comes with several string macros, such as:

@b_str

This string macro constructs byte arrays instead of strings. The contents of the string, encoded as UTF-8, will be used as the array of bytes. This can be useful for interfacing with low-level APIs, many of which work with byte arrays instead of strings.

julia> b"Hello World!"
12-element Array{UInt8,1}:
 0x48
 0x65
 0x6c
 0x6c
 0x6f
 0x20
 0x57
 0x6f
 0x72
 0x6c
 0x64
 0x21

@big_str

This macro will return a BigInt or a BigFloat parsed from the string it's given.

julia> big"1"
1

julia> big"1.0"
1.000000000000000000000000000000000000000000000000000000000000000000000000000000

This macro exists because big(0.1) does not behave as one might initially expect: the 0.1 is a Float64 approximation of true 0.1 (1//10), and promoting that to BigFloat will keep the approximation error of Float64. Using the macro will parse 0.1 directly to a BigFloat, reducing the approximation error.

julia> big(0.1)
1.000000000000000055511151231257827021181583404541015625000000000000000000000000e-01

julia> big"0.1"
1.000000000000000000000000000000000000000000000000000000000000000000000000000002e-01

@doc_str

This string macro constructs Base.Markdown.MD objects, which are used in the internal documentation system to provide rich-text documentation for any environment. These MD objects render well in a terminal:

terminal markdown documentation renders well

and also in a browser:

browser markdown documentation renders well

@html_str

This string macro constructs HTML string literals, which render nicely in a browser:

html string macro rendering nicely in a browser

@ip_str

This string macro constructs IP address literals. It works with both IPv4 and IPv6:

julia> ip"127.0.0.1"
ip"127.0.0.1"

julia> ip"::"
ip"::"

@r_str

This string macro constructs Regex literals.

@s_str

This string macro constructs SubstitutionString literals, which work together with Regex literals to allow more advanced textual substitution.

@text_str

This string macro is similar in spirit to @doc_str and @html_str, but does not have any fancy formatting features:

plain text in the browser

@v_str

This string macro constructs VersionNumber literals. See Version Numbers for a description of what they are and how to use them.

@MIME_str

This string macro constructs the singleton types of MIME types. For instance, MIME"text/plain" is the type of MIME("text/plain").