Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 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 reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...