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 inI()to match it literally, as a shorthand forfixed = TRUE.- negate
If
TRUE, test thatxdoes not matchpattern. As a shorthand, negating the pattern itself (has_match(x, !pattern)) sets this toTRUE. Prefer either form over negating the whole call (!has_match(x, p)), sincenegatealso makes the failure message showx.- fixed
Whether to match
patternliterally instead of as a regular expression. Defaults toTRUEwhenpatternis wrapped inI(), sohas_match(x, I(p))is a shorthand forhas_match(x, p, fixed = TRUE).- perl
Whether to use Perl-compatible regular expressions (which also enables the dotall flag). Defaults to
FALSEfor afixedsearch, which uses neither.- ...
Additional arguments passed to
grepl()(e.g.,ignore.case = TRUE).
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)
})