Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

r - How do I deal with special characters like ^$.?*|+()[{ in my regex?

I want to match a regular expression special character, ^$.?*|+()[{. I tried:

x <- "a[b"
grepl("[", x)
## Error: invalid regular expression '[', reason 'Missing ']''

(Equivalently stringr::str_detect(x, "[") or stringi::stri_detect_regex(x, "[").)

Doubling the value to escape it doesn't work:

grepl("[[", x)
## Error: invalid regular expression '[[', reason 'Missing ']''

Neither does using a backslash:

grepl("[", x)
## Error: '[' is an unrecognized escape in character string starting ""["

How do I match special characters?


Some special cases of this in questions that are old and well written enough for it to be cheeky to close as duplicates of this:
Escaped Periods In R Regular Expressions
How to escape a question mark in R?
escaping pipe ("|") in a regex

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...