Working with text
Text in Ant is a string: an immutable sequence of Unicode code points, stored as UTF-8. Four namespaces work with it:
- String holds the operations on text: measuring, searching, splitting, trimming, case, and conversion to and from numbers.
- Regex matches patterns, written as a literal such as
/\d+/or compiled from data. - Bytes holds binary data, and the UTF-8 bytes of a string when you need them.
- Encoding writes bytes as hex or Base64 text and reads them back.
Lengths, indices, and slices count code points, not bytes. What a reader sees as one character can be several code points, which String.graphemes keeps together:
let word = "naïve"
word.length() // 5
word.toBytes().length() // 6
"👍🏽".length() // 2
"👍🏽".graphemes().length() // 1There is no character type. A for loop gives each code point as a one-code-point string, and the class tests such as String.isDigit take one:
for c in "a1b2" {
if c.isDigit() {
println(c)
}
}1
2Writing strings
A string between double quotes takes escapes and interpolates any value with ${...}. A raw string between backticks keeps every character as written, which suits paths and templates:
let n = 3
"${n} ants\tin a row" // "3 ants\tin a row"
`C:\temp\${n}` // "C:\\temp\\\${n}"Both kinds may span lines, and each line break is one \n:
let banner = "Ant
===
"
print(banner)Ant
===There is no format string. Interpolate the result of String.fromInt or String.fromFloat, and pad it to a width:
let total = 12.5
"total: ${String.fromFloat(total, 2).padStart(8)}" // "total: 12.50"
"#${String.fromInt(255, 16).padStart(6, "0")}" // "#0000ff"String or Regex
For fixed text, use the String functions. They match code point by code point, with no pattern syntax to escape:
let line = "error: disk full"
line.startsWith("error:") // true
line.replace("full", "busy") // "error: disk busy"
line.cut(": ")?.after // "disk full"For a shape rather than fixed text, such as "digits", "a word", or "any run of spaces", use a pattern:
let line = "took 120 ms, then 45 ms"
Regex.test(/\d+ ms/, line) // true
Regex.findAll(/\d+/, line) | Array.map({ x.text }) // ["120", "45"]
Regex.replace(/\s+/, line, " ") // "took 120 ms, then 45 ms"A pattern is the first argument of every Regex function that matches (test, find, findAll, replace, replaceFirst, replaceWith, split), so the string goes second. A pipe carries the pattern, not the string, into a Regex function; pipe the results onward instead.
A replacement refers to a group by number or name. In a double-quoted replacement, ${...} interpolates; write \${name} or use a raw string:
Regex.replace(/(\d+)-(\d+)-(\d+)/, "2026-11-14", `$3.$2.$1`) // "14.11.2026"
Regex.replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, "2026-11-14", "\${d}.\${m}") // "14.11"Strings and bytes
A string is text, and Bytes is whatever a file, a connection, or a digest holds. Text becomes bytes through String.toBytes, and bytes become text through String.fromBytes, which is null when they are not UTF-8, or String.fromBytesLossy, which writes U+FFFD for each bad sequence:
let data = "héllo".toBytes()
data // Bytes(68 c3 a9 6c 6c 6f)
String.fromBytes(data) // "héllo"
Bytes.fromArray([0x61, 0xff]) | String.fromBytes() // null
Bytes.fromArray([0x61, 0xff]) | String.fromBytesLossy() // "a�"To put bytes where only text fits, such as JSON, a URL, or a header, encode them as hex or Base64. The decoders return a Result, since the text may not be valid:
let data = "hi?".toBytes()
Encoding.toHex(data) // "68693f"
Encoding.toBase64(data) // "aGk/"
"aGk/" | Encoding.fromBase64() | Result.map(String.fromBytes) // Ok{ value: "hi?" }
Encoding.fromHex("6g") // Err{ error: Error{ message: "invalid byte: U+0067 'g'" } }Putting them together
Parse a log line with named groups, then clean up the parts with String functions:
type LogLine = { level: string, message: string }
func parse(line: string): LogLine | null {
let m = Regex.find(/^\[(?<level>\w+)\]\s*(?<message>.*)$/, line)
if m == null {
return null
}
LogLine{
level: (m.named["level"] ?? "").toUpper(),
message: (m.named["message"] ?? "").trim(),
}
}
for line in "[warn] disk almost full \nnoise\n[info] started\n".lines() {
let entry = parse(line)
if entry != null {
println("${entry.level.padEnd(5)} ${entry.message}")
}
}WARN disk almost full
INFO startedHash a message and show the digest as hex, the way checksums are published:
let digest = "hello" | String.toBytes() | Crypto.sha256() | Encoding.toHex()
println(digest)2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824Compare names the way a reader would, regardless of case and of how an accent was typed:
func sameName(a: string, b: string): bool {
a.trim().normalize("NFC").equalFold(b.trim().normalize("NFC"))
}
println(sameName("José", " JOSE\u{301} "))
println(sameName("Straße", "STRASSE"))true
trueFunctions by job
Building text
- String.from: any value, as
printlnand interpolation render it - String.fromInt: an integer in a base
- String.fromFloat: a float with a fixed number of decimals
- String.repeat:
ncopies of a string - String.concat: pieces one after the other
- String.join: pieces with a separator between them
- String.padStart, String.padEnd: padding up to a width
Size and pieces
- String.length: the number of code points
- String.isEmpty: whether there are none
- String.slice: the code points from one index up to another
- String.chars: one string per code point
- String.graphemes: one string per character as a reader sees it
Searching
- String.contains: whether fixed text occurs
- String.startsWith, String.endsWith: whether text begins or ends with fixed text
- String.indexOf, String.lastIndexOf: the first or last index of fixed text, or
null - String.count: how many times fixed text occurs, without overlap
- Regex.test: whether a pattern matches anywhere
- Regex.find: the leftmost match, with its groups, or
null - Regex.findAll: every match, left to right
Splitting
- String.split: the pieces between each separator
- String.cut: the two sides of the first separator, as String.Cut
- String.fields: the runs between white space
- String.lines: the lines of a text
- Regex.split: the pieces between the matches of a pattern
Trimming
- String.trim, String.trimStart, String.trimEnd: white space removed at both ends, the start, or the end
- String.trimPrefix, String.trimSuffix: a prefix or suffix removed once
Replacing
- String.replace, String.replaceFirst: every or the first occurrence of fixed text replaced
- Regex.replace, Regex.replaceFirst: every or the first match replaced, with
$1and${name}expanded - Regex.replaceWith: every match replaced by what a function returns
Case and normalization
- String.toUpper, String.toLower: upper or lower case
- String.foldCase: a key in which case does not matter
- String.equalFold: whether two strings are equal without regard to case
- String.normalize: one of the four Unicode normalization forms
Character classes
- String.isDigit, String.isNumber: decimal digits, or any numbers
- String.isLetter, String.isUpper, String.isLower: letters, upper-case, or lower-case letters
- String.isSpace: white space
- String.isPunct, String.isSymbol, String.isMark: punctuation, symbols, or marks such as combining accents
- String.isControl, String.isGraphic, String.isPrint: control, graphic, or printable code points
- String.category: the general category of one code point
- String.inScript: whether one code point belongs to a script
Numbers from text
- String.toInt, String.toUint, String.toFloat: a number read from text, or
null
Patterns
- Regex.compile: a pattern from a string, or an
Err - Regex.escape: text with every metacharacter escaped, to match it literally
- Regex.source, Regex.flags: the source and flags of a pattern
- Regex.Pattern: a compiled regular expression
- Regex.Match: one match, with its text, indices, and groups
Code points and bytes
- String.codePoint, String.fromCodePoint: one code point to an
intand back - String.toCodePoints, String.fromCodePoints: every code point to an
intand back - String.toBytes: the UTF-8 bytes of a string
- String.fromBytes: bytes as text, or
nullwhen they are not UTF-8 - String.fromBytesLossy: bytes as text, with U+FFFD for what is not UTF-8
Hex and Base64
- Encoding.toHex, Encoding.fromHex: bytes as two hex digits each, and back
- Encoding.toBase64, Encoding.fromBase64: bytes as Base64, standard or URL-safe, and back
Building and changing bytes
- Bytes.new: a number of zero bytes
- Bytes.fromArray: bytes from an array of integers
- Bytes.concat: an array of
Bytesjoined in order - Bytes.clone: a copy
- Bytes.push, Bytes.extend: append one byte, or other bytes
- Bytes.pop, Bytes.truncate: remove the last byte, or keep the first ones
- Bytes.fill, Bytes.copy: overwrite a range with one byte, or with other bytes
Reading bytes
- Bytes.length: the number of bytes
- Bytes.slice: a copy of a range
- Bytes.indexOf: the index of other bytes from an offset, or
null - Bytes.startsWith, Bytes.endsWith: whether a prefix or suffix is there
- Bytes.same: whether two names hold one collection
- Bytes.toArray: the bytes as an
Array[byte]
Numbers in bytes
- Bytes.read, Bytes.write: a fixed-size number at an index, in a stated byte order
- Bytes.append: a number added at the end
- Bytes.sizeOf: the bytes a number type takes
- Bytes.Order: Bytes.BigEndian or Bytes.LittleEndian
Mistakes to avoid
A string cannot be indexed. Slice it, or index its chars:
let s = "ant"
println(s[0]) // error: string cannot be indexedlet s = "ant"
s.slice(0, 1) // "a"
s.chars()[0] // "a"join is a String function that takes an array, so a dot call on the array does not find it. End the chain with a pipe:
let parts = ["a", "b"]
println(parts.join(",")) // error: Array[string] has no field or function joinlet parts = ["a", "b"]
parts | String.join(",") // "a,b"== compares code points, so it neither ignores case nor joins the two spellings of é. Compare through String.equalFold and String.normalize:
"Ant" == "ANT" // false
"Ant".equalFold("ANT") // true
"\u{E9}" == "e\u{301}" // false
"\u{E9}".normalize("NFC") == "e\u{301}".normalize("NFC") // trueThe i flag of a pattern folds case one code point at a time, so it misses what String.equalFold accepts:
Regex.test(/straße/i, "STRASSE") // false
"straße".equalFold("STRASSE") // trueString.length counts code points, which differs from the bytes a file or a protocol counts. Count the bytes of String.toBytes:
"日本".length() // 2
"日本".toBytes().length() // 6\d, \w, and \s in a pattern match ASCII only. Use \p{Nd} for digits and \pL for letters in any script:
Regex.test(/^\w+$/, "héllo") // false
Regex.test(/^\pL+$/, "héllo") // true
Regex.test(/^\d+$/, "٣٤") // false
Regex.test(/^\p{Nd}+$/, "٣٤") // trueSee also
- Strings: how strings, characters, and bytes fit together
- String literals, Raw strings, Regular expression literals
- Numbers: parsing and printing numbers
- Data formats: JSON, CSV, and digests
