Strings
Core.AbstractString — TypeThe AbstractString type is the supertype of all string implementations in Julia. Strings are encodings of sequences of Unicode code points as represented by the AbstractChar type. Julia makes a few assumptions about strings:
- Strings are encoded in terms of fixed-size "code units"
- Code units can be extracted with
codeunit(s, i) - The first code unit has index
1 - The last code unit has index
ncodeunits(s) - Any index
isuch that1 ≤ i ≤ ncodeunits(s)is in bounds
- Code units can be extracted with
- String indexing is done in terms of these code units:
- Characters are extracted by
s[i]with a valid string indexi - Each
AbstractCharin a string is encoded by one or more code units - Only the index of the first code unit of an
AbstractCharis a valid index - The encoding of an
AbstractCharis independent of what precedes or follows it - String encodings are [self-synchronizing] – i.e.
isvalid(s, i)is O(1)
- Characters are extracted by
[self-synchronizing]: https://en.wikipedia.org/wiki/Self-synchronizing_code
Some string functions that extract code units, characters or substrings from strings error if you pass them out-of-bounds or invalid string indices. This includes codeunit(s, i) and s[i]. Functions that do string index arithmetic take a more relaxed approach to indexing and give you the closest valid string index when in-bounds, or when out-of-bounds, behave as if there were an infinite number of characters padding each side of the string. Usually these imaginary padding characters have code unit length 1 but string types may choose different "imaginary" character sizes as makes sense for their implementations (e.g. substrings may pass index arithmetic through to the underlying string they provide a view into). Relaxed indexing functions include those intended for index arithmetic: thisind, nextind and prevind. This model allows index arithmetic to work with out-of- bounds indices as intermediate values so long as one never uses them to retrieve a character, which often helps avoid needing to code around edge cases.
See also codeunit, ncodeunits, thisind, nextind, prevind.
Core.AbstractChar — TypeThe AbstractChar type is the supertype of all character implementations in Julia. A character represents a Unicode code point, and can be converted to an integer via the codepoint function in order to obtain the numerical value of the code point, or constructed from the same integer. These numerical values determine how characters are compared with < and ==, for example. New T <: AbstractChar types should define a codepoint(::T) method and a T(::UInt32) constructor, at minimum.
A given AbstractChar subtype may be capable of representing only a subset of Unicode, in which case conversion from an unsupported UInt32 value may throw an error. Conversely, the built-in Char type represents a superset of Unicode (in order to losslessly encode invalid byte streams), in which case conversion of a non-Unicode value to UInt32 throws an error. The isvalid function can be used to check which codepoints are representable in a given AbstractChar type.
Internally, an AbstractChar type may use a variety of encodings. Conversion via codepoint(char) will not reveal this encoding because it always returns the Unicode value of the character. print(io, c) of any c::AbstractChar produces an encoding determined by io (UTF-8 for all built-in IO types), via conversion to Char if necessary.
write(io, c), in contrast, may emit an encoding depending on typeof(c), and read(io, typeof(c)) should read the same encoding as write. New AbstractChar types must provide their own implementations of write and read.
Core.Char — TypeChar(c::Union{Number,AbstractChar})Char is a 32-bit AbstractChar type that is the default representation of characters in Julia. Char is the type used for character literals like 'x' and it is also the element type of String.
In order to losslessly represent arbitrary byte streams stored in a String, a Char value may store information that cannot be converted to a Unicode codepoint — converting such a Char to UInt32 will throw an error. The isvalid(c::Char) function can be used to query whether c represents a valid Unicode character.
Base.codepoint — Functioncodepoint(c::AbstractChar) -> IntegerReturn the Unicode codepoint (an unsigned integer) corresponding to the character c (or throw an exception if c does not represent a valid character). For Char, this is a UInt32 value, but AbstractChar types that represent only a subset of Unicode may return a different-sized integer (e.g. UInt8).
Base.length — Methodlength(s::AbstractString) -> Int
length(s::AbstractString, i::Integer, j::Integer) -> IntReturn the number of characters in string s from indices i through j.
This is computed as the number of code unit indices from i to j which are valid character indices. With only a single string argument, this computes the number of characters in the entire string. With i and j arguments it computes the number of indices between i and j inclusive that are valid indices in the string s. In addition to in-bounds values, i may take the out-of-bounds value ncodeunits(s) + 1 and j may take the out-of-bounds value 0.
The time complexity of this operation is linear in general. That is, it will take the time proportional to the number of bytes or characters in the string because it counts the value on the fly. This is in contrast to the method for arrays, which is a constant-time operation.
See also isvalid, ncodeunits, lastindex, thisind, nextind, prevind.
Examples
julia> length("jμΛIα")
5Base.sizeof — Methodsizeof(str::AbstractString)Size, in bytes, of the string str. Equal to the number of code units in str multiplied by the size, in bytes, of one code unit in str.
Examples
julia> sizeof("")
0
julia> sizeof("∀")
3Base.:* — Method*(s::Union{AbstractString, AbstractChar}, t::Union{AbstractString, AbstractChar}...) -> AbstractStringConcatenate strings and/or characters, producing a String. This is equivalent to calling the string function on the arguments. Concatenation of built-in string types always produces a value of type String but other string types may choose to return a string of a different type as appropriate.
Examples
julia> "Hello " * "world"
"Hello world"
julia> 'j' * "ulia"
"julia"Base.:^ — Method^(s::Union{AbstractString,AbstractChar}, n::Integer) -> AbstractStringRepeat a string or character n times. This can also be written as repeat(s, n).
See also repeat.
Examples
julia> "Test "^3
"Test Test Test "Base.string — Functionstring(n::Integer; base::Integer = 10, pad::Integer = 1)Convert an integer n to a string in the given base, optionally specifying a number of digits to pad to.
See also digits, bitstring, count_zeros.
Examples
julia> string(5, base = 13, pad = 4)
"0005"
julia> string(-13, base = 5, pad = 4)
"-0023"string(xs...)Create a string from any values using the print function.
string should usually not be defined directly. Instead, define a method print(io::IO, x::MyType). If string(x) for a certain type needs to be highly efficient, then it may make sense to add a method to string and define print(io::IO, x::MyType) = print(io, string(x)) to ensure the functions are consistent.
See also: String, repr, sprint, show.
Examples
julia> string("a", 1, true)
"a1true"Base.repeat — Methodrepeat(s::AbstractString, r::Integer)Repeat a string r times. This can be written as s^r.
See also ^.
Examples
julia> repeat("ha", 3)
"hahaha"Base.repeat — Methodrepeat(c::AbstractChar, r::Integer) -> StringRepeat a character r times. This can equivalently be accomplished by calling c^r.
Examples
julia> repeat('A', 3)
"AAA"Base.repr — Methodrepr(x; context=nothing)Create a string from any value using the show function. You should not add methods to repr; define a show method instead.
The optional keyword argument context can be set to a :key=>value pair, a tuple of :key=>value pairs, or an IO or IOContext object whose attributes are used for the I/O stream passed to show.
Note that repr(x) is usually similar to how the value of x would be entered in Julia. See also repr(MIME("text/plain"), x) to instead return a "pretty-printed" version of x designed more for human consumption, equivalent to the REPL display of x.
Passing a tuple to keyword context requires Julia 1.7 or later.
Examples
julia> repr(1)
"1"
julia> repr(zeros(3))
"[0.0, 0.0, 0.0]"
julia> repr(big(1/3))
"0.333333333333333314829616256247390992939472198486328125"
julia> repr(big(1/3), context=:compact => true)
"0.333333"
Core.String — MethodString(s::AbstractString)Create a new String from an existing AbstractString.
Base.SubString — TypeSubString(s::AbstractString, i::Integer, j::Integer=lastindex(s))
SubString(s::AbstractString, r::UnitRange{<:Integer})Like getindex, but returns a view into the parent string s within range i:j or r respectively instead of making a copy.
The @views macro converts any string slices s[i:j] into substrings SubString(s, i, j) in a block of code.
Examples
julia> SubString("abc", 1, 2)
"ab"
julia> SubString("abc", 1:2)
"ab"
julia> SubString("abc", 2)
"bc"Base.LazyString — TypeLazyString <: AbstractStringA lazy representation of string interpolation. This is useful when a string needs to be constructed in a context where performing the actual interpolation and string construction is unnecessary or undesirable (e.g. in error paths of functions).
This type is designed to be cheap to construct at runtime, trying to offload as much work as possible to either the macro or later printing operations.
Examples
julia> n = 5; str = LazyString("n is ", n)
"n is 5"See also @lazy_str.
LazyString requires Julia 1.8 or later.
Extended help
Safety properties for concurrent programs
A lazy string itself does not introduce any concurrency problems even if it is printed in multiple Julia tasks. However, if print methods on a captured value can have a concurrency issue when invoked without synchronizations, printing the lazy string may cause an issue. Furthermore, the print methods on the captured values may be invoked multiple times, though only exactly one result will be returned.
LazyString is safe in the above sense in Julia 1.9 and later.
Base.@lazy_str — Macrolazy"str"Create a LazyString using regular string interpolation syntax. Note that interpolations are evaluated at LazyString construction time, but printing is delayed until the first access to the string.
See LazyString documentation for the safety properties for concurrent programs.
Examples
julia> n = 5; str = lazy"n is $n"
"n is 5"
julia> typeof(str)
LazyStringlazy"str" requires Julia 1.8 or later.
Base.transcode — Functiontranscode(T, src)Convert string data between Unicode encodings. src is either a String or a Vector{UIntXX} of UTF-XX code units, where XX is 8, 16, or 32. T indicates the encoding of the return value: String to return a (UTF-8 encoded) String or UIntXX to return a Vector{UIntXX} of UTF-XX data. (The alias Cwchar_t can also be used as the integer type, for converting wchar_t* strings used by external C libraries.)
The transcode function succeeds as long as the input data can be reasonably represented in the target encoding; it always succeeds for conversions between UTF-XX encodings, even for invalid Unicode data.
Only conversion to/from UTF-8 is currently supported.
Examples
julia> str = "αβγ"
"αβγ"
julia> transcode(UInt16, str)
3-element Vector{UInt16}:
0x03b1
0x03b2
0x03b3
julia> transcode(String, transcode(UInt16, str))
"αβγ"Base.unsafe_string — Functionunsafe_string(p::Ptr{UInt8}, [length::Integer])Copy a string from the address of a C-style (NUL-terminated) string encoded as UTF-8. (The pointer can be safely freed afterwards.) If length is specified (the length of the data in bytes), the string does not have to be NUL-terminated.
This function is labeled "unsafe" because it will crash if p is not a valid memory address to data of the requested length.
Base.ncodeunits — Methodncodeunits(s::AbstractString) -> IntReturn the number of code units in a string. Indices that are in bounds to access this string must satisfy 1 ≤ i ≤ ncodeunits(s). Not all such indices are valid – they may not be the start of a character, but they will return a code unit value when calling codeunit(s,i).
Examples
julia> ncodeunits("The Julia Language")
18
julia> ncodeunits("∫eˣ")
6
julia> ncodeunits('∫'), ncodeunits('e'), ncodeunits('ˣ')
(3, 1, 2)See also codeunit, checkbounds, sizeof, length, lastindex.
Base.codeunit — Functioncodeunit(s::AbstractString) -> Type{<:Union{UInt8, UInt16, UInt32}}Return the code unit type of the given string object. For ASCII, Latin-1, or UTF-8 encoded strings, this would be UInt8; for UCS-2 and UTF-16 it would be UInt16; for UTF-32 it would be UInt32. The code unit type need not be limited to these three types, but it's hard to think of widely used string encodings that don't use one of these units. codeunit(s) is the same as typeof(codeunit(s,1)) when s is a non-empty string.
See also ncodeunits.
codeunit(s::AbstractString, i::Integer) -> Union{UInt8, UInt16, UInt32}Return the code unit value in the string s at index i. Note that
codeunit(s, i) :: codeunit(s)I.e. the value returned by codeunit(s, i) is of the type returned by codeunit(s).
Examples
julia> a = codeunit("Hello", 2)
0x65
julia> typeof(a)
UInt8See also ncodeunits, checkbounds.
Base.codeunits — Functioncodeunits(s::AbstractString)Obtain a vector-like object containing the code units of a string. Returns a CodeUnits wrapper by default, but codeunits may optionally be defined for new string types if necessary.
Examples
julia> codeunits("Juλia")
6-element Base.CodeUnits{UInt8, String}:
0x4a
0x75
0xce
0xbb
0x69
0x61Base.ascii — Functionascii(s::AbstractString)Convert a string to String type and check that it contains only ASCII data, otherwise throwing an ArgumentError indicating the position of the first non-ASCII byte.
See also the isascii predicate to filter or replace non-ASCII characters.
Examples
julia> ascii("abcdeγfgh")
ERROR: ArgumentError: invalid ASCII at index 6 in "abcdeγfgh"
Stacktrace:
[...]
julia> ascii("abcdefgh")
"abcdefgh"Base.Regex — TypeRegex(pattern[, flags]) <: AbstractPatternA type representing a regular expression. Regex objects can be used to match strings with match.
Regex objects can be created using the @r_str string macro. The Regex(pattern[, flags]) constructor is usually used if the pattern string needs to be interpolated. See the documentation of the string macro for details on flags.
To escape interpolated variables use \Q and \E (e.g. Regex("\\Q$x\\E"))
Base.@r_str — Macro@r_str -> RegexConstruct a regex, such as r"^[a-z]*$", without interpolation and unescaping (except for quotation mark " which still has to be escaped). The regex also accepts one or more flags, listed after the ending quote, to change its behaviour:
ienables case-insensitive matchingmtreats the^and$tokens as matching the start and end of individual lines, as opposed to the whole string.sallows the.modifier to match newlines.xenables "comment mode": whitespace is enabled except when escaped with\, and#is treated as starting a comment.aenables ASCII mode (disablesUTFandUCPmodes). By default\B,\b,\D,\d,\S,\s,\W,\w, etc. match based on Unicode character properties. With this option, these sequences only match ASCII characters. This includes\ualso, which will emit the specified character value directly as a single byte, and not attempt to encode it into UTF-8. Importantly, this option allows matching against invalid UTF-8 strings, by treating both matcher and target as simple bytes (as if they were ISO/IEC 8859-1 / Latin-1 bytes) instead of as character encodings. In this case, this option is often combined withs. This option can be further refined by starting the pattern with (UCP) or (UTF).
See Regex if interpolation is needed.
Examples
julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n")
RegexMatch("angry,\nBad world")This regex has the first three flags enabled.
Base.SubstitutionString — TypeSubstitutionString(substr) <: AbstractStringStores the given string substr as a SubstitutionString, for use in regular expression substitutions. Most commonly constructed using the @s_str macro.
Examples
julia> SubstitutionString("Hello \\g<name>, it's \\1")
s"Hello \g<name>, it's \1"
julia> subst = s"Hello \g<name>, it's \1"
s"Hello \g<name>, it's \1"
julia> typeof(subst)
SubstitutionString{String}Base.@s_str — Macro@s_str -> SubstitutionStringConstruct a substitution string, used for regular expression substitutions. Within the string, sequences of the form \N refer to the Nth capture group in the regex, and \g<groupname> refers to a named capture group with name groupname.
Examples
julia> msg = "#Hello# from Julia";
julia> replace(msg, r"#(.+)# from (?<from>\w+)" => s"FROM: \g<from>; MESSAGE: \1")
"FROM: Julia; MESSAGE: Hello"Base.@raw_str — Macro@raw_str -> StringCreate a raw string without interpolation and unescaping. The exception is that quotation marks still must be escaped. Backslashes escape both quotation marks and other backslashes, but only when a sequence of backslashes precedes a quote character. Thus, 2n backslashes followed by a quote encodes n backslashes and the end of the literal while 2n+1 backslashes followed by a quote encodes n backslashes followed by a quote character.
Examples
julia> println(raw"\ $x")
\ $x
julia> println(raw"\"")
"
julia> println(raw"\\\"")
\"
julia> println(raw"\\x \\\"")
\\x \"Base.@b_str — Macro@b_strCreate an immutable byte (UInt8) vector using string syntax.
Examples
julia> v = b"12\x01\x02"
4-element Base.CodeUnits{UInt8, String}:
0x31
0x32
0x01
0x02
julia> v[2]
0x32Base.Docs.@html_str — Macro@html_str -> Docs.HTMLCreate an HTML object from a literal string.
Examples
julia> html"Julia"
HTML{String}("Julia")Base.Docs.@text_str — Macro@text_str -> Docs.TextCreate a Text object from a literal string.
Examples
julia> text"Julia"
JuliaBase.isvalid — Methodisvalid(value) -> BoolReturn true if the given value is valid for its type, which currently can be either AbstractChar or String or SubString{String}.
Examples
julia> isvalid(Char(0xd800))
false
julia> isvalid(SubString(String(UInt8[0xfe,0x80,0x80,0x80,0x80,0x80]),1,2))
false
julia> isvalid(Char(0xd799))
trueBase.isvalid — Methodisvalid(T, value) -> BoolReturn true if the given value is valid for that type. Types currently can be either AbstractChar or String. Values for AbstractChar can be of type AbstractChar or UInt32. Values for String can be of that type, SubString{String}, Vector{UInt8}, or a contiguous subarray thereof.
Examples
julia> isvalid(Char, 0xd800)
false
julia> isvalid(String, SubString("thisisvalid",1,5))
true
julia> isvalid(Char, 0xd799)
trueSupport for subarray values was added in Julia 1.6.
Base.isvalid — Methodisvalid(s::AbstractString, i::Integer) -> BoolPredicate indicating whether the given index is the start of the encoding of a character in s or not. If isvalid(s, i) is true then s[i] will return the character whose encoding starts at that index, if it's false, then s[i] will raise an invalid index error or a bounds error depending on if i is in bounds. In order for isvalid(s, i) to be an O(1) function, the encoding of s must be self-synchronizing. This is a basic assumption of Julia's generic string support.
See also getindex, iterate, thisind, nextind, prevind, length.
Examples
julia> str = "αβγdef";
julia> isvalid(str, 1)
true
julia> str[1]
'α': Unicode U+03B1 (category Ll: Letter, lowercase)
julia> isvalid(str, 2)
false
julia> str[2]
ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'α', [3]=>'β'
Stacktrace:
[...]Base.match — Functionmatch(r::Regex, s::AbstractString[, idx::Integer[, addopts]])Search for the first match of the regular expression r in s and return a RegexMatch object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing m.match and the captured sequences can be retrieved by accessing m.captures The optional idx argument specifies an index at which to start the search.
Examples
julia> rx = r"a(.)a"
r"a(.)a"
julia> m = match(rx, "cabac")
RegexMatch("aba", 1="b")
julia> m.captures
1-element Vector{Union{Nothing, SubString{String}}}:
"b"
julia> m.match
"aba"
julia> match(rx, "cabac", 3) === nothing
trueBase.eachmatch — Functioneachmatch(r::Regex, s::AbstractString; overlap::Bool=false)Search for all matches of the regular expression r in s and return an iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.
Examples
julia> rx = r"a.a"
r"a.a"
julia> m = eachmatch(rx, "a1a2a3a")
Base.RegexMatchIterator(r"a.a", "a1a2a3a", false)
julia> collect(m)
2-element Vector{RegexMatch}:
RegexMatch("a1a")
RegexMatch("a3a")
julia> collect(eachmatch(rx, "a1a2a3a", overlap = true))
3-element Vector{RegexMatch}:
RegexMatch("a1a")
RegexMatch("a2a")
RegexMatch("a3a")Base.RegexMatch — TypeRegexMatch <: AbstractMatchA type representing a single match to a Regex found in a string. Typically created from the match function.
The match field stores the substring of the entire matched string. The captures field stores the substrings for each capture group, indexed by number. To index by capture group name, the entire match object should be indexed instead, as shown in the examples. The location of the start of the match is stored in the offset field. The offsets field stores the locations of the start of each capture group, with 0 denoting a group that was not captured.
This type can be used as an iterator over the capture groups of the Regex, yielding the substrings captured in each group. Because of this, the captures of a match can be destructured. If a group was not captured, nothing will be yielded instead of a substring.
Methods that accept a RegexMatch object are defined for iterate, length, eltype, keys, haskey, and getindex, where keys are the the names or numbers of a capture group. See keys for more information.
Examples
julia> m = match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30 in the morning")
RegexMatch("11:30", hour="11", minute="30", 3=nothing)
julia> m.match
"11:30"
julia> m.captures
3-element Vector{Union{Nothing, SubString{String}}}:
"11"
"30"
nothing
julia> m["minute"]
"30"
julia> hr, min, ampm = m; # destructure capture groups by iteration
julia> hr
"11"Base.keys — Methodkeys(m::RegexMatch) -> VectorReturn a vector of keys for all capture groups of the underlying regex. A key is included even if the capture group fails to match. That is, idx will be in the return value even if m[idx] == nothing.
Unnamed capture groups will have integer keys corresponding to their index. Named capture groups will have string keys.
This method was added in Julia 1.7
Examples
julia> keys(match(r"(?<hour>\d+):(?<minute>\d+)(am|pm)?", "11:30"))
3-element Vector{Any}:
"hour"
"minute"
3Base.isless — Methodisless(a::AbstractString, b::AbstractString) -> BoolTest whether string a comes before string b in alphabetical order (technically, in lexicographical order by Unicode code points).
Examples
julia> isless("a", "b")
true
julia> isless("β", "α")
false
julia> isless("a", "a")
falseBase.:== — Method==(a::AbstractString, b::AbstractString) -> BoolTest whether two strings are equal character by character (technically, Unicode code point by code point).
Examples
julia> "abc" == "abc"
true
julia> "abc" == "αβγ"
falseBase.cmp — Methodcmp(a::AbstractString, b::AbstractString) -> IntCompare two strings. Return 0 if both strings have the same length and the character at each index is the same in both strings. Return -1 if a is a prefix of b, or if a comes before b in alphabetical order. Return 1 if b is a prefix of a, or if b comes before a in alphabetical order (technically, lexicographical order by Unicode code points).
Examples
julia> cmp("abc", "abc")
0
julia> cmp("ab", "abc")
-1
julia> cmp("abc", "ab")
1
julia> cmp("ab", "ac")
-1
julia> cmp("ac", "ab")
1
julia> cmp("α", "a")
1
julia> cmp("b", "β")
-1Base.lpad — Functionlpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> StringStringify s and pad the resulting string on the left with p to make it n characters (in textwidth) long. If s is already n characters long, an equal string is returned. Pad with spaces by default.
Examples
julia> lpad("March", 10)
" March"In Julia 1.7, this function was changed to use textwidth rather than a raw character (codepoint) count.
Base.rpad — Functionrpad(s, n::Integer, p::Union{AbstractChar,AbstractString}=' ') -> StringStringify s and pad the resulting string on the right with p to make it n characters (in textwidth) long. If s is already n characters long, an equal string is returned. Pad with spaces by default.
Examples
julia> rpad("March", 20)
"March "In Julia 1.7, this function was changed to use textwidth rather than a raw character (codepoint) count.
Base.findfirst — Methodfindfirst(pattern::AbstractString, string::AbstractString)
findfirst(pattern::AbstractPattern, string::String)Find the first occurrence of pattern in string. Equivalent to findnext(pattern, string, firstindex(s)).
Examples
julia> findfirst("z", "Hello to the world") # returns nothing, but not printed in the REPL
julia> findfirst("Julia", "JuliaLang")
1:5Base.findnext — Methodfindnext(pattern::AbstractString, string::AbstractString, start::Integer)
findnext(pattern::AbstractPattern, string::String, start::Integer)Find the next occurrence of pattern in string starting at position start. pattern can be either a string, or a regular expression, in which case string must be of type String.
The return value is a range of indices where the matching sequence is found, such that s[findnext(x, s, i)] == x:
findnext("substring", string, i) == start:stop such that string[start:stop] == "substring" and i <= start, or nothing if unmatched.
Examples
julia> findnext("z", "Hello to the world", 1) === nothing
true
julia> findnext("o", "Hello to the world", 6)
8:8
julia> findnext("Lang", "JuliaLang", 2)
6:9Base.findnext — Methodfindnext(ch::AbstractChar, string::AbstractString, start::Integer)Find the next occurrence of character ch in string starting at position start.
This method requires at least Julia 1.3.
Examples
julia> findnext('z', "Hello to the world", 1) === nothing
true
julia> findnext('o', "Hello to the world", 6)
8Base.findlast — Methodfindlast(pattern::AbstractString, string::AbstractString)Find the last occurrence of pattern in string. Equivalent to findprev(pattern, string, lastindex(string)).
Examples
julia> findlast("o", "Hello to the world")
15:15
julia> findfirst("Julia", "JuliaLang")
1:5Base.findlast — Methodfindlast(ch::AbstractChar, string::AbstractString)Find the last occurrence of character ch in string.
This method requires at least Julia 1.3.
Examples
julia> findlast('p', "happy")
4
julia> findlast('z', "happy") === nothing
trueBase.findprev — Methodfindprev(pattern::AbstractString, string::AbstractString, start::Integer)Find the previous occurrence of pattern in string starting at position start.
The return value is a range of indices where the matching sequence is found, such that s[findprev(x, s, i)] == x:
findprev("substring", string, i) == start:stop such that string[start:stop] == "substring" and stop <= i, or nothing if unmatched.
Examples
julia> findprev("z", "Hello to the world", 18) === nothing
true
julia> findprev("o", "Hello to the world", 18)
15:15
julia> findprev("Julia", "JuliaLang", 6)
1:5Base.occursin — Functionoccursin(needle::Union{AbstractString,AbstractPattern,AbstractChar}, haystack::AbstractString)Determine whether the first argument is a substring of the second. If needle is a regular expression, checks whether haystack contains a match.
Examples
julia> occursin("Julia", "JuliaLang is pretty cool!")
true
julia> occursin('a', "JuliaLang is pretty cool!")
true
julia> occursin(r"a.a", "aba")
true
julia> occursin(r"a.a", "abba")
falseSee also contains.
occursin(haystack)Create a function that checks whether its argument occurs in haystack, i.e. a function equivalent to needle -> occursin(needle, haystack).
The returned function is of type Base.Fix2{typeof(occursin)}.
This method requires Julia 1.6 or later.
Examples
julia> search_f = occursin("JuliaLang is a programming language");
julia> search_f("JuliaLang")
true
julia> search_f("Python")
falseBase.reverse — Methodreverse(s::AbstractString) -> AbstractStringReverses a string. Technically, this function reverses the codepoints in a string and its main utility is for reversed-order string processing, especially for reversed regular-expression searches. See also reverseind to convert indices in s to indices in reverse(s) and vice-versa, and graphemes from module Unicode to operate on user-visible "characters" (graphemes) rather than codepoints. See also Iterators.reverse for reverse-order iteration without making a copy. Custom string types must implement the reverse function themselves and should typically return a string with the same type and encoding. If they return a string with a different encoding, they must also override reverseind for that string type to satisfy s[reverseind(s,i)] == reverse(s)[i].
Examples
julia> reverse("JuliaLang")
"gnaLailuJ"The examples below may be rendered differently on different systems. The comments indicate how they're supposed to be rendered
Combining characters can lead to surprising results:
julia> reverse("ax̂e") # hat is above x in the input, above e in the output
"êxa"
julia> using Unicode
julia> join(reverse(collect(graphemes("ax̂e")))) # reverses graphemes; hat is above x in both in- and output
"ex̂a"Base.replace — Methodreplace([io::IO], s::AbstractString, pat=>r, [pat2=>r2, ...]; [count::Integer])Search for the given pattern pat in s, and replace each occurrence with r. If count is provided, replace at most count occurrences. pat may be a single character, a vector or a set of characters, a string, or a regular expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring (when pat is a AbstractPattern or AbstractString) or character (when pat is an AbstractChar or a collection of AbstractChar). If pat is a regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding matched text. To remove instances of pat from string, set r to the empty String ("").
The return value is a new string after the replacements. If the io::IO argument is supplied, the transformed string is instead written to io (returning io). (For example, this can be used in conjunction with an IOBuffer to re-use a pre-allocated buffer array in-place.)
Multiple patterns can be specified, and they will be applied left-to-right simultaneously, so only one pattern will be applied to any character, and the patterns will only be applied to the input text, not the replacements.
Support for multiple patterns requires version 1.7.
The io::IO argument requires version 1.10.
Examples
julia> replace("Python is a programming language.", "Python" => "Julia")
"Julia is a programming language."
julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
"The slow foxes run quickly."
julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
"The foxes run quickly."
julia> replace("The quick foxes run quickly.", r"fox(es)?" => s"bus\1")
"The quick buses run quickly."
julia> replace("abcabc", "a" => "b", "b" => "c", r".+" => "a")
"bca"Base.eachsplit — Functioneachsplit(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
eachsplit(str::AbstractString; limit::Integer=0, keepempty::Bool=false)Split str on occurrences of the delimiter(s) dlm and return an iterator over the substrings. dlm can be any of the formats allowed by findnext's first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.
If dlm is omitted, it defaults to isspace.
The optional keyword arguments are:
limit: the maximum size of the result.limit=0implies no maximum (default)keepempty: whether empty fields should be kept in the result. Default isfalsewithout adlmargument,truewith adlmargument.
See also split.
The eachsplit function requires at least Julia 1.8.
Examples
julia> a = "Ma.rch"
"Ma.rch"
julia> b = eachsplit(a, ".")
Base.SplitIterator{String, String}("Ma.rch", ".", 0, true)
julia> collect(b)
2-element Vector{SubString{String}}:
"Ma"
"rch"Base.split — Functionsplit(str::AbstractString, dlm; limit::Integer=0, keepempty::Bool=true)
split(str::AbstractString; limit::Integer=0, keepempty::Bool=false)Split str into an array of substrings on occurrences of the delimiter(s) dlm. dlm can be any of the formats allowed by findnext's first argument (i.e. as a string, regular expression or a function), or as a single character or collection of characters.
If dlm is omitted, it defaults to isspace.
The optional keyword arguments are:
limit: the maximum size of the result.limit=0implies no maximum (default)keepempty: whether empty fields should be kept in the result. Default isfalsewithout adlmargument,truewith adlmargument.
Examples
julia> a = "Ma.rch"
"Ma.rch"
julia> split(a, ".")
2-element Vector{SubString{String}}:
"Ma"
"rch"Base.rsplit — Functionrsplit(s::AbstractString; limit::Integer=0, keepempty::Bool=false)
rsplit(s::AbstractString, chars; limit::Integer=0, keepempty::Bool=true)Similar to split, but starting from the end of the string.
Examples
julia> a = "M.a.r.c.h"
"M.a.r.c.h"
julia> rsplit(a, ".")
5-element Vector{SubString{String}}:
"M"
"a"
"r"
"c"
"h"
julia> rsplit(a, "."; limit=1)
1-element Vector{SubString{String}}:
"M.a.r.c.h"
julia> rsplit(a, "."; limit=2)
2-element Vector{SubString{String}}:
"M.a.r.c"
"h"Base.strip — Functionstrip([pred=isspace,] str::AbstractString) -> SubString
strip(str::AbstractString, chars) -> SubStringRemove leading and trailing characters from str, either those specified by chars or those for which the function pred returns true.
The default behaviour is to remove leading and trailing whitespace and delimiters: see isspace for precise details.
The optional chars argument specifies which characters to remove: it can be a single character, vector or set of characters.
The method which accepts a predicate function requires Julia 1.2 or later.
Examples
julia> strip("{3, 5}\n", ['{', '}', '\n'])
"3, 5"Base.lstrip — Functionlstrip([pred=isspace,] str::AbstractString) -> SubString
lstrip(str::AbstractString, chars) -> SubStringRemove leading characters from str, either those specified by chars or those for which the function pred returns true.
The default behaviour is to remove leading whitespace and delimiters: see isspace for precise details.
The optional chars argument specifies which characters to remove: it can be a single character, or a vector or set of characters.
Examples
julia> a = lpad("March", 20)
" March"
julia> lstrip(a)
"March"Base.rstrip — Functionrstrip([pred=isspace,] str::AbstractString) -> SubString
rstrip(str::AbstractString, chars) -> SubStringRemove trailing characters from str, either those specified by chars or those for which the function pred returns true.
The default behaviour is to remove trailing whitespace and delimiters: see isspace for precise details.
The optional chars argument specifies which characters to remove: it can be a single character, or a vector or set of characters.
Examples
julia> a = rpad("March", 20)
"March "
julia> rstrip(a)
"March"Base.startswith — Functionstartswith(s::AbstractString, prefix::AbstractString)Return true if s starts with prefix. If prefix is a vector or set of characters, test whether the first character of s belongs to that set.
Examples
julia> startswith("JuliaLang", "Julia")
truestartswith(io::IO, prefix::Union{AbstractString,Base.Chars})Check if an IO object starts with a prefix. See also peek.
startswith(prefix)Create a function that checks whether its argument starts with prefix, i.e. a function equivalent to y -> startswith(y, prefix).
The returned function is of type Base.Fix2{typeof(startswith)}, which can be used to implement specialized methods.
The single argument startswith(prefix) requires at least Julia 1.5.
Examples
julia> startswith("Julia")("JuliaLang")
true
julia> startswith("Julia")("Ends with Julia")
falsestartswith(s::AbstractString, prefix::Regex)Return true if s starts with the regex pattern, prefix.
startswith does not compile the anchoring into the regular expression, but instead passes the anchoring as match_option to PCRE. If compile time is amortized, occursin(r"^...", s) is faster than startswith(s, r"...").
See also occursin and endswith.
This method requires at least Julia 1.2.
Examples
julia> startswith("JuliaLang", r"Julia|Romeo")
trueBase.endswith — Functionendswith(s::AbstractString, suffix::AbstractString)Return true if s ends with suffix. If suffix is a vector or set of characters, test whether the last character of s belongs to that set.
See also startswith, contains.
Examples
julia> endswith("Sunday", "day")
trueendswith(suffix)Create a function that checks whether its argument ends with suffix, i.e. a function equivalent to y -> endswith(y, suffix).
The returned function is of type Base.Fix2{typeof(endswith)}, which can be used to implement specialized methods.
The single argument endswith(suffix) requires at least Julia 1.5.
Examples
julia> endswith("Julia")("Ends with Julia")
true
julia> endswith("Julia")("JuliaLang")
falseendswith(s::AbstractString, suffix::Regex)Return true if s ends with the regex pattern, suffix.
endswith does not compile the anchoring into the regular expression, but instead passes the anchoring as match_option to PCRE. If compile time is amortized, occursin(r"...$", s) is faster than endswith(s, r"...").
See also occursin and startswith.
This method requires at least Julia 1.2.
Examples
julia> endswith("JuliaLang", r"Lang|Roberts")
trueBase.contains — Functioncontains(haystack::AbstractString, needle)Return true if haystack contains needle. This is the same as occursin(needle, haystack), but is provided for consistency with startswith(haystack, needle) and endswith(haystack, needle).
See also occursin, in, issubset.
Examples
julia> contains("JuliaLang is pretty cool!", "Julia")
true
julia> contains("JuliaLang is pretty cool!", 'a')
true
julia> contains("aba", r"a.a")
true
julia> contains("abba", r"a.a")
falseThe contains function requires at least Julia 1.5.
contains(needle)Create a function that checks whether its argument contains needle, i.e. a function equivalent to haystack -> contains(haystack, needle).
The returned function is of type Base.Fix2{typeof(contains)}, which can be used to implement specialized methods.
Base.first — Methodfirst(s::AbstractString, n::Integer)Get a string consisting of the first n characters of s.
Examples
julia> first("∀ϵ≠0: ϵ²>0", 0)
""
julia> first("∀ϵ≠0: ϵ²>0", 1)
"∀"
julia> first("∀ϵ≠0: ϵ²>0", 3)
"∀ϵ≠"Base.last — Methodlast(s::AbstractString, n::Integer)Get a string consisting of the last n characters of s.
Examples
julia> last("∀ϵ≠0: ϵ²>0", 0)
""
julia> last("∀ϵ≠0: ϵ²>0", 1)
"0"
julia> last("∀ϵ≠0: ϵ²>0", 3)
"²>0"Base.Unicode.uppercase — Functionuppercase(c::AbstractChar)Convert c to uppercase.
See also lowercase, titlecase.
Examples
julia> uppercase('a')
'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
julia> uppercase('ê')
'Ê': Unicode U+00CA (category Lu: Letter, uppercase)uppercase(s::AbstractString)Return s with all characters converted to uppercase.
See also lowercase, titlecase, uppercasefirst.
Examples
julia> uppercase("Julia")
"JULIA"Base.Unicode.lowercase — Functionlowercase(c::AbstractChar)Convert c to lowercase.
See also uppercase, titlecase.
Examples
julia> lowercase('A')
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
julia> lowercase('Ö')
'ö': Unicode U+00F6 (category Ll: Letter, lowercase)lowercase(s::AbstractString)Return s with all characters converted to lowercase.
See also uppercase, titlecase, lowercasefirst.
Examples
julia> lowercase("STRINGS AND THINGS")
"strings and things"Base.Unicode.titlecase — Functiontitlecase(c::AbstractChar)Convert c to titlecase. This may differ from uppercase for digraphs, compare the example below.
See also uppercase, lowercase.
Examples
julia> titlecase('a')
'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
julia> titlecase('dž')
'Dž': Unicode U+01C5 (category Lt: Letter, titlecase)
julia> uppercase('dž')
'DŽ': Unicode U+01C4 (category Lu: Letter, uppercase)titlecase(s::AbstractString; [wordsep::Function], strict::Bool=true) -> StringCapitalize the first character of each word in s; if strict is true, every other character is converted to lowercase, otherwise they are left unchanged. By default, all non-letters beginning a new grapheme are considered as word separators; a predicate can be passed as the wordsep keyword to determine which characters should be considered as word separators. See also uppercasefirst to capitalize only the first character in s.
See also uppercase, lowercase, uppercasefirst.
Examples
julia> titlecase("the JULIA programming language")
"The Julia Programming Language"
julia> titlecase("ISS - international space station", strict=false)
"ISS - International Space Station"
julia> titlecase("a-a b-b", wordsep = c->c==' ')
"A-a B-b"Base.Unicode.uppercasefirst — Functionuppercasefirst(s::AbstractString) -> StringReturn s with the first character converted to uppercase (technically "title case" for Unicode). See also titlecase to capitalize the first character of every word in s.
See also lowercasefirst, uppercase, lowercase, titlecase.
Examples
julia> uppercasefirst("python")
"Python"Base.Unicode.lowercasefirst — Functionlowercasefirst(s::AbstractString)Return s with the first character converted to lowercase.
See also uppercasefirst, uppercase, lowercase, titlecase.
Examples
julia> lowercasefirst("Julia")
"julia"Base.join — Functionjoin([io::IO,] iterator [, delim [, last]])Join any iterator into a single string, inserting the given delimiter (if any) between adjacent items. If last is given, it will be used instead of delim between the last two items. Each item of iterator is converted to a string via print(io::IOBuffer, x). If io is given, the result is written to io rather than returned as a String.
Examples
julia> join(["apples", "bananas", "pineapples"], ", ", " and ")
"apples, bananas and pineapples"
julia> join([1,2,3,4,5])
"12345"Base.chop — Functionchop(s::AbstractString; head::Integer = 0, tail::Integer = 1)Remove the first head and the last tail characters from s. The call chop(s) removes the last character from s. If it is requested to remove more characters than length(s) then an empty string is returned.
See also chomp, startswith, first.
Examples
julia> a = "March"
"March"
julia> chop(a)
"Marc"
julia> chop(a, head = 1, tail = 2)
"ar"
julia> chop(a, head = 5, tail = 5)
""Base.chopprefix — Functionchopprefix(s::AbstractString, prefix::Union{AbstractString,Regex}) -> SubStringRemove the prefix prefix from s. If s does not start with prefix, a string equal to s is returned.
See also chopsuffix.
This function is available as of Julia 1.8.
Examples
julia> chopprefix("Hamburger", "Ham")
"burger"
julia> chopprefix("Hamburger", "hotdog")
"Hamburger"Base.chopsuffix — Functionchopsuffix(s::AbstractString, suffix::Union{AbstractString,Regex}) -> SubStringRemove the suffix suffix from s. If s does not end with suffix, a string equal to s is returned.
See also chopprefix.
This function is available as of Julia 1.8.
Examples
julia> chopsuffix("Hamburger", "er")
"Hamburg"
julia> chopsuffix("Hamburger", "hotdog")
"Hamburger"Base.chomp — Functionchomp(s::AbstractString) -> SubStringRemove a single trailing newline from a string.
See also chop.
Examples
julia> chomp("Hello\n")
"Hello"Base.thisind — Functionthisind(s::AbstractString, i::Integer) -> IntIf i is in bounds in s return the index of the start of the character whose encoding code unit i is part of. In other words, if i is the start of a character, return i; if i is not the start of a character, rewind until the start of a character and return that index. If i is equal to 0 or ncodeunits(s)+1 return i. In all other cases throw BoundsError.
Examples
julia> thisind("α", 0)
0
julia> thisind("α", 1)
1
julia> thisind("α", 2)
1
julia> thisind("α", 3)
3
julia> thisind("α", 4)
ERROR: BoundsError: attempt to access 2-codeunit String at index [4]
[...]
julia> thisind("α", -1)
ERROR: BoundsError: attempt to access 2-codeunit String at index [-1]
[...]Base.nextind — Functionnextind(str::AbstractString, i::Integer, n::Integer=1) -> IntCase
n == 1If
iis in bounds insreturn the index of the start of the character whose encoding starts after indexi. In other words, ifiis the start of a character, return the start of the next character; ifiis not the start of a character, move forward until the start of a character and return that index. Ifiis equal to0return1. Ifiis in bounds but greater or equal tolastindex(str)returnncodeunits(str)+1. Otherwise throwBoundsError.Case
n > 1Behaves like applying
ntimesnextindforn==1. The only difference is that ifnis so large that applyingnextindwould reachncodeunits(str)+1then each remaining iteration increases the returned value by1. This means that in this casenextindcan return a value greater thanncodeunits(str)+1.Case
n == 0Return
ionly ifiis a valid index insor is equal to0. OtherwiseStringIndexErrororBoundsErroris thrown.
Examples
julia> nextind("α", 0)
1
julia> nextind("α", 1)
3
julia> nextind("α", 3)
ERROR: BoundsError: attempt to access 2-codeunit String at index [3]
[...]
julia> nextind("α", 0, 2)
3
julia> nextind("α", 1, 2)
4Base.prevind — Functionprevind(str::AbstractString, i::Integer, n::Integer=1) -> IntCase
n == 1If
iis in bounds insreturn the index of the start of the character whose encoding starts before indexi. In other words, ifiis the start of a character, return the start of the previous character; ifiis not the start of a character, rewind until the start of a character and return that index. Ifiis equal to1return0. Ifiis equal toncodeunits(str)+1returnlastindex(str). Otherwise throwBoundsError.Case
n > 1Behaves like applying
ntimesprevindforn==1. The only difference is that ifnis so large that applyingprevindwould reach0then each remaining iteration decreases the returned value by1. This means that in this caseprevindcan return a negative value.Case
n == 0Return
ionly ifiis a valid index instror is equal toncodeunits(str)+1. OtherwiseStringIndexErrororBoundsErroris thrown.
Examples
julia> prevind("α", 3)
1
julia> prevind("α", 1)
0
julia> prevind("α", 0)
ERROR: BoundsError: attempt to access 2-codeunit String at index [0]
[...]
julia> prevind("α", 2, 2)
0
julia> prevind("α", 2, 3)
-1Base.Unicode.textwidth — Functiontextwidth(c)Give the number of columns needed to print a character.
Examples
julia> textwidth('α')
1
julia> textwidth('⛵')
2textwidth(s::AbstractString)Give the number of columns needed to print a string.
Examples
julia> textwidth("March")
5Base.isascii — Functionisascii(c::Union{AbstractChar,AbstractString}) -> BoolTest whether a character belongs to the ASCII character set, or whether this is true for all elements of a string.
Examples
julia> isascii('a')
true
julia> isascii('α')
false
julia> isascii("abc")
true
julia> isascii("αβγ")
falseFor example, isascii can be used as a predicate function for filter or replace to remove or replace non-ASCII characters, respectively:
julia> filter(isascii, "abcdeγfgh") # discard non-ASCII chars
"abcdefgh"
julia> replace("abcdeγfgh", !isascii=>' ') # replace non-ASCII chars with spaces
"abcde fgh"isascii(cu::AbstractVector{CU}) where {CU <: Integer} -> BoolTest whether all values in the vector belong to the ASCII character set (0x00 to 0x7f). This function is intended to be used by other string implementations that need a fast ASCII check.
Base.Unicode.iscntrl — Functioniscntrl(c::AbstractChar) -> BoolTests whether a character is a control character. Control characters are the non-printing characters of the Latin-1 subset of Unicode.
Examples
julia> iscntrl('\x01')
true
julia> iscntrl('a')
falseBase.Unicode.isdigit — Functionisdigit(c::AbstractChar) -> BoolTests whether a character is a decimal digit (0-9).
See also: isletter.
Examples
julia> isdigit('❤')
false
julia> isdigit('9')
true
julia> isdigit('α')
falseBase.Unicode.isletter — Functionisletter(c::AbstractChar) -> BoolTest whether a character is a letter. A character is classified as a letter if it belongs to the Unicode general category Letter, i.e. a character whose category code begins with 'L'.
See also: isdigit.
Examples
julia> isletter('❤')
false
julia> isletter('α')
true
julia> isletter('9')
falseBase.Unicode.islowercase — Functionislowercase(c::AbstractChar) -> BoolTests whether a character is a lowercase letter (according to the Unicode standard's Lowercase derived property).
See also isuppercase.
Examples
julia> islowercase('α')
true
julia> islowercase('Γ')
false
julia> islowercase('❤')
falseBase.Unicode.isnumeric — Functionisnumeric(c::AbstractChar) -> BoolTests whether a character is numeric. A character is classified as numeric if it belongs to the Unicode general category Number, i.e. a character whose category code begins with 'N'.
Note that this broad category includes characters such as ¾ and ௰. Use isdigit to check whether a character is a decimal digit between 0 and 9.
Examples
julia> isnumeric('௰')
true
julia> isnumeric('9')
true
julia> isnumeric('α')
false
julia> isnumeric('❤')
falseBase.Unicode.isprint — Functionisprint(c::AbstractChar) -> BoolTests whether a character is printable, including spaces, but not a control character.
Examples
julia> isprint('\x01')
false
julia> isprint('A')
trueBase.Unicode.ispunct — Functionispunct(c::AbstractChar) -> BoolTests whether a character belongs to the Unicode general category Punctuation, i.e. a character whose category code begins with 'P'.
Examples
julia> ispunct('α')
false
julia> ispunct('/')
true
julia> ispunct(';')
trueBase.Unicode.isspace — Functionisspace(c::AbstractChar) -> BoolTests whether a character is any whitespace character. Includes ASCII characters '\t', '\n', '\v', '\f', '\r', and ' ', Latin-1 character U+0085, and characters in Unicode category Zs.
Examples
julia> isspace('\n')
true
julia> isspace('\r')
true
julia> isspace(' ')
true
julia> isspace('\x20')
trueBase.Unicode.isuppercase — Functionisuppercase(c::AbstractChar) -> BoolTests whether a character is an uppercase letter (according to the Unicode standard's Uppercase derived property).
See also islowercase.
Examples
julia> isuppercase('γ')
false
julia> isuppercase('Γ')
true
julia> isuppercase('❤')
falseBase.Unicode.isxdigit — Functionisxdigit(c::AbstractChar) -> BoolTest whether a character is a valid hexadecimal digit. Note that this does not include x (as in the standard 0x prefix).
Examples
julia> isxdigit('a')
true
julia> isxdigit('x')
falseBase.escape_string — Functionescape_string(str::AbstractString[, esc]; keep = ())::AbstractString
escape_string(io, str::AbstractString[, esc]; keep = ())::NothingGeneral escaping of traditional C and Unicode escape sequences. The first form returns the escaped string, the second prints the result to io.
Backslashes (\) are escaped with a double-backslash ("\\"). Non-printable characters are escaped either with their standard C escape codes, "\0" for NUL (if unambiguous), unicode code point ("\u" prefix) or hex ("\x" prefix).
The optional esc argument specifies any additional characters that should also be escaped by a prepending backslash (" is also escaped by default in the first form).
The argument keep specifies a collection of characters which are to be kept as they are. Notice that esc has precedence here.
See also unescape_string for the reverse operation.
The keep argument is available as of Julia 1.7.
Examples
julia> escape_string("aaa\nbbb")
"aaa\\nbbb"
julia> escape_string("aaa\nbbb"; keep = '\n')
"aaa\nbbb"
julia> escape_string("\xfe\xff") # invalid utf-8
"\\xfe\\xff"
julia> escape_string(string('\u2135','\0')) # unambiguous
"ℵ\\0"
julia> escape_string(string('\u2135','\0','0')) # \0 would be ambiguous
"ℵ\\x000"Base.unescape_string — Functionunescape_string(str::AbstractString, keep = ())::AbstractString
unescape_string(io, s::AbstractString, keep = ())::NothingGeneral unescaping of traditional C and Unicode escape sequences. The first form returns the escaped string, the second prints the result to io. The argument keep specifies a collection of characters which (along with backlashes) are to be kept as they are.
The following escape sequences are recognised:
- Escaped backslash (
\\) - Escaped double-quote (
\") - Standard C escape sequences (
\a,\b,\t,\n,\v,\f,\r,\e) - Unicode BMP code points (
\uwith 1-4 trailing hex digits) - All Unicode code points (
\Uwith 1-8 trailing hex digits; max value = 0010ffff) - Hex bytes (
\xwith 1-2 trailing hex digits) - Octal bytes (
\with 1-3 trailing octal digits)
See also escape_string.
Examples
julia> unescape_string("aaa\\nbbb") # C escape sequence
"aaa\nbbb"
julia> unescape_string("\\u03c0") # unicode
"π"
julia> unescape_string("\\101") # octal
"A"
julia> unescape_string("aaa \\g \\n", ['g']) # using `keep` argument
"aaa \\g \n"