[R] problems with a regex search, grepl, and double-quote marks from word processor
Chris Ryan
cwr @end|ng |rom @gency@t@t|@t|c@|@com
Sat Nov 14 21:12:47 CET 2026
I am doing some text searching. Always a risky endeavor.
I want to find records in which a free-text field contains the string
"sicke" or "sickal" (not my actual words of interest, of course), but
then exclude such records if the string "not" is within 6 words (forward
or backward) of the otherwise-qualifying "sicke" or "sickal". I think I
have the first step figured out pretty well. It's with the exclusion
step that I have problems.
Here is my code:
## adjust the width of the "window" around "sicke" and "sickal"
exclusion_tuner <- 6
## a regex to put into grepl
exclusion_regex <- paste0("\\b(?:not\\W+(?:\\w+\\W+){0,",
exclusion_tuner, "}sick(e|al)|sick(e|al)\\W+(?:\\w+\\W+){0,",
exclusion_tuner, "}not)\\b")
## my exclusion function, using grepl
my.exclusion.f <- function(string){grepl(exclusion_regex, string,
ignore.case = TRUE)}
Now I test it against a string.
The line below should yield FALSE (meaning not excluded), because the
words "sicke" and "not" are more than 6 words apart from each other (in
either direction). And indeed it does.
my.exclusion.f("unit 2 arrives mares eat oats and sicke does eat oats
and little lambs eat ivy. I swim pretty good. Your cash is not good at
the bar")
Here is the problem:
The database system from where I get my data sometimes includes direct
quotes of what someone said. The quotation marks used seem to be like
those in word processing software. Look at the sentence about swimming:
my.exclusion.f("unit 2 arrives mares eat oats and sicke does eat oats
and little lambs eat ivy. “I swim pretty good“. Your cash is not good at
the bar")
I want the above to also yield FALSE, but it yields TRUE.
If I replace those quotation marks with single quotes from my text
editor, like 'I swim pretty good', then I get the expected result of
FALSE, as in the line below.
my.exclusion.f("unit 2 arrives mares eat oats and suicide does eat oats
and little lambs eat ivy. 'I swim pretty good'. Your cash is not good at
the bar")
I know little about character encoding, like ASCII or UTF-8 and the
like, but is that the issue here? Do I need to somehow remove or change
any double-quotes from the data first? Or is there something wrong with
my regex?
Thanks.
--Chris Ryan
---
Agency Statistical Consulting, LLC
Helping those in public service get the most from their data.
www.agencystatistical.com
Public GnuPG email encryption key at
https://keys.openpgp.org
9E53101D261BEC070CFF1A0DC8BC50E715A672A0
More information about the R-help
mailing list