Skip to content

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:

ant
let word = "naïve"
word.length()             // 5
word.toBytes().length()   // 6
"👍🏽".length()             // 2
"👍🏽".graphemes().length() // 1

There 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:

ant
for c in "a1b2" {
  if c.isDigit() {
    println(c)
  }
}
text
1
2

Writing 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:

ant
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:

ant
let banner = "Ant
  ===
"
print(banner)
text
Ant
  ===

There is no format string. Interpolate the result of String.fromInt or String.fromFloat, and pad it to a width:

ant
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:

ant
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:

ant
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:

ant
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:

ant
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:

ant
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:

ant
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}")
  }
}
text
WARN  disk almost full
INFO  started

Hash a message and show the digest as hex, the way checksums are published:

ant
let digest = "hello" | String.toBytes() | Crypto.sha256() | Encoding.toHex()
println(digest)
text
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Compare names the way a reader would, regardless of case and of how an accent was typed:

ant
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"))
text
true
true

Functions by job ​

Building text ​

Size and pieces ​

Searching ​

Splitting ​

Trimming ​

Replacing ​

Case and normalization ​

Character classes ​

Numbers from text ​

Patterns ​

Code points and bytes ​

Hex and Base64 ​

Building and changing bytes ​

Reading bytes ​

Numbers in bytes ​

Mistakes to avoid ​

A string cannot be indexed. Slice it, or index its chars:

ant
let s = "ant"
println(s[0]) // error: string cannot be indexed
ant
let 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:

ant
let parts = ["a", "b"]
println(parts.join(",")) // error: Array[string] has no field or function join
ant
let 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" == "ANT"                                           // false
"Ant".equalFold("ANT")                                   // true
"\u{E9}" == "e\u{301}"                                   // false
"\u{E9}".normalize("NFC") == "e\u{301}".normalize("NFC") // true

The i flag of a pattern folds case one code point at a time, so it misses what String.equalFold accepts:

ant
Regex.test(/straße/i, "STRASSE") // false
"straße".equalFold("STRASSE")    // true

String.length counts code points, which differs from the bytes a file or a protocol counts. Count the bytes of String.toBytes:

ant
"日本".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:

ant
Regex.test(/^\w+$/, "héllo")  // false
Regex.test(/^\pL+$/, "héllo") // true
Regex.test(/^\d+$/, "٣٤")     // false
Regex.test(/^\p{Nd}+$/, "٣٤") // true

See also ​