has_match: Test whether a string matches a regular expression

View source: R/testit.R

has_matchR Documentation

Test whether a string matches a regular expression

Description

Check whether x matches the regular expression pattern. This is intended for use inside assert(): unlike grepl(), which only returns TRUE/FALSE and hides the input on failure, a failing has_match() shows the actual string so you can see what was produced.

Usage

has_match(x, pattern, negate = FALSE, perl = TRUE, ...)

Arguments

x

A character vector. Multiple elements are collapsed into a single string (separated by newlines) before matching.

pattern

A regular expression. By default, matching uses Perl mode with the "dotall" flag enabled, so . also matches newlines, which is convenient for searching multi-line text such as rendered HTML.

negate

If TRUE, test that x does not match pattern. Prefer this over negating with ! (e.g. !has_match(x, p)), since negate also makes the failure message show x.

perl

Whether to use Perl-compatible regular expressions (which also enables the dotall flag).

...

Additional arguments passed to grepl() (e.g., ignore.case = TRUE).

Value

TRUE if x matches pattern (or does not match it when negate = TRUE), otherwise FALSE.

Examples

library(testit)
assert('the page has a script but no style', {
  html = '<html>\n<script>x</script>\n</html>'
  (has_match(html, '<script>.*</script>'))
  (has_match(html, '<style>', negate = TRUE))
})

testit documentation built on Oct. 16, 2026, 1:06 a.m.

Related to has_match in testit...