regex

open fun Field<T, String?>.regex(pattern: String, caseInsensitive: Boolean = false, dotAll: Boolean = false, extended: Boolean = false, matchEachLine: Boolean = false)(source)
open fun KProperty1<T, String?>.regex(pattern: String, caseInsensitive: Boolean = false, dotAll: Boolean = false, extended: Boolean = false, matchEachLine: Boolean = false)(source)

Matches documents where the field corresponds to a given regex expression.

Example

class User(
val name: String,
)

collection.find {
User::name.regex("John .*")
}

Indexing

If possible, prefer using a "^" prefix. For example, if we know that a pattern will only be present at the start of a string, "^foo" will use indexes, whereas "foo" will not.

Avoid using .* at the start and end of a pattern. "foo" is identical to "foo.*", but the former can use indexes and the latter cannot.

External resources

Parameters

caseInsensitive

If true, the result is matched even if its case doesn't match. Note that this also disables index usage (even case-insensitive indexes) and ignores collation.

dotAll

If true, the dot character (.) can match newlines.

extended

If true, whitespace (except in character classes) is ignored, and segments starting from an unescaped pound (#) until a newline are ignored, similarly to a Python comment.

User::name.regex(
pattern = """
abc # This is a comment, it's not part of the pattern
123
""".trimIndent(),
extended = true,
)

which is identical to the non-extended pattern "abc123".

matchEachLine

If true, the special characters ^ and $ match the beginning and end of each line, instead of matching the beginning and end of the entire string. Therefore, "^S" will match "First line\nSecond line", which would not match otherwise.