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,
  fixed = inherits(pattern, "AsIs"),
  perl = !fixed,
  ...
)

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. Wrap the pattern in I() to match it literally, as a shorthand for fixed = TRUE.

negate

If TRUE, test that x does not match pattern. As a shorthand, negating the pattern itself (has_match(x, !pattern)) sets this to TRUE. Prefer either form over negating the whole call (!has_match(x, p)), since negate also makes the failure message show x.

fixed

Whether to match pattern literally instead of as a regular expression. Defaults to TRUE when pattern is wrapped in I(), so has_match(x, I(p)) is a shorthand for has_match(x, p, fixed = TRUE).

perl

Whether to use Perl-compatible regular expressions (which also enables the dotall flag). Defaults to FALSE for a fixed search, which uses neither.

...

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))
  (has_match(html, !'<style>'))  # same, via the !pattern shorthand
  (has_match(html, I('<script>x</script>')))  # literal match (fixed = TRUE)
})

testit documentation built on Nov. 3, 2026, 1:07 a.m.

Related to has_match in testit...