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

前端 未结 2 1295
花落未央
花落未央 2020-11-21 04:36

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

x <- \"a[b\"
grepl(\"[\", x)
## Error: invalid regular expre         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:24

    I think the easiest way to match the characters like

    \^$.?*|+()[
    

    are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:

    > library(stringr)
    > colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
    

    This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\ to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp to see more info about this.

    https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf

提交回复
热议问题