Knitting qmd with intended PCRE pattern compilation error produces wrong output

I have defined a function just.matches that basically just combines regmatches and gregexpr into one function:

just.matches <- function (search.expression, corpus, ...) {
    regmatches(corpus, gregexpr(search.expression, corpus, ...))
}

In a teaching context where we haven't gotten to regexes yet, I want to show that for some characters, one needs to prefix a double backslash because otherwise one will get an error. So I want to use this:

#| error: true
example <- "This is an example of a word in curly brackets: *cheese*."
just.matches("*", example) # doesn't work

But while I get the intended error in RStudio's console ...

Warning: PCRE pattern compilation error
'quantifier does not follow a repeatable item'
at ''Error in gregexpr(search.expr, corpus.v, perl = perl, ...) :
invalid regular expression '
'

... when I knit the qmd, I get this instead:

[[1]]
[1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
[26] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
[51] "" "" "" "" "" "" ""

What am I doing wrong? Thanks a lot!

I don't know. I expanded your example and got the following. Maybe it helps.

---
title: "Untitled"
format: html
---

## Quarto


```{r}
just.matches <- function (search.expression, corpus, ...) {
    regmatches(corpus, gregexpr(search.expression, corpus, ...))
}
just.matches1 <- function (search.expression, corpus, ...) {
    gregexpr(search.expression, corpus, ...) 
}
```

```{r}
#| error: true
example <- "This is an example of a word in curly brackets: *cheese*."
just.matches1("*", example) # doesn't work
just.matches("*", example) # doesn't work
just.matches1("\\*", example) # doesn't work
just.matches("\\*", example) # doesn't work
```

result:

It did help, if only because when I re-ran ,y stuff and yours, I noticed I was so stupid as to forget to set perl=TRUE for gregexpr in the body of my function definition ... :frowning: But thanks, it did make me see my mistake, somehow!

2 Likes

Beat me to it. You had me at PCRE

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.