我正在嘗試在句子中搜索單詞(不區分大小寫)和標點符號。以下函式適用于單詞,但需要\\適用于點,例如;因此它會導致不需要的行為 - 見下文:
fun <- function(text, search) {
gsub(paste0("\\b(", search, ")\\b"), paste0("<mark>", '\\1', "</mark>"),
text, ignore.case = T)
}
> fun("this is a test.", ".")
[1] "this<mark> </mark>is<mark> </mark><mark>a</mark><mark> </mark>test<mark>.</mark>"
> fun("(this is a test)", ")")
[1] "(this is a test<mark></mark>"
期待:
> fun("this is a test.", ".")
[1] "this is a test<mark>.</mark>"
> fun("(this is a test)", ")")
[1] "(this is a test<mark>)</mark>"
什么是最好的方法——正則運算式?- 在字串中搜索單詞和標點符號?
uj5u.com熱心網友回復:
你需要
- 轉義特殊字符
- 動態自適應詞邊界
- 由于動態自適應字邊界是環視,您需要傳遞
perl=TRUE到gsub.
請參閱R 代碼:
## Escaping function
regex.escape <- function(string) {
gsub("([][{}() *^$|\\\\?.])", "\\\\\\1", string)
}
fun <- function(text, search) {
gsub(paste0("(?!\\B\\w)(", regex.escape(search), ")(?<!\\w\\B)"), "<mark>\\1</mark>",
text, ignore.case = TRUE, perl=TRUE)
}
fun("this is a test.", ".")
# [1] "this is a test<mark>.</mark>"
fun("(this is a test)", ")")
# [1] "(this is a test<mark>)</mark>"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476785.html
上一篇:提取大寫單詞直到第一個小寫字母
