r - 使用正则表达式替换区分大小写的断字
问题描述
我正在尝试用德语输入清理 R 中的一些文本。
library(tidyverse)
bye_bye_hyphenation <- function(x){
# removes words separated by hyphenation f.e. due to PDF input
# eliminate line breaks
# first group for characters (incl. European ones) (\\1), dash and following whitespace,
# second group for characters (\\2) (incl. European ones)
stringr::str_replace_all(x, "([a-z|A-Z\x7f-\xff]{1,})\\-[\\s]{1,}([a-z|A-Z\x7f-\xff]{1,})", "\\1\\2")
}
# this works correctly
"Ex-\n ample" %>%
bye_bye_hyphenation()
#> [1] "Example"
# this should stay the same, `Regierungsund` should not be
# concatenated
"Regierungs- und Verwaltungsgesetz" %>%
bye_bye_hyphenation()
#> [1] "Regierungsund Verwaltungsgesetz"
由reprex 包(v0.3.0)于 2019 年 6 月 19 日创建
有人知道如何使整个正则表达式区分大小写,这样它就不会在第二种情况下触发,即每当单词und
出现在破折号和空格之后?
解决方案
也许您可以使用负或正前瞻(参见Regex lookahead、lookbehind 和 atomic groups 等)。如果后面没有单词“und”,则下面的正则表达式将删除一个破折号,后跟一个潜在的换行符或空格,否则只删除一个换行符:
library(stringr)
string1 <- "Ex- ample"
string2 <- "Ex-\n ample"
string3 <- "Regierungs- und Verwaltungsgesetz"
string4 <- "Regierungs-\n und Verwaltungsgesetz"
pattern <- "(-\\n?\\s?(?!\\n?\\s?und))|(\\n(?=\\s?und))"
str_remove(string1, pattern)
#> [1] "Example"
str_remove(string2, pattern)
#> [1] "Example"
str_remove(string3, pattern)
#> [1] "Regierungs- und Verwaltungsgesetz"
str_remove(string4, pattern)
#> [1] "Regierungs- und Verwaltungsgesetz"
由reprex 包(v0.3.0)于 2019 年 6 月 19 日创建
推荐阅读
- javascript - 如何将其中一个 div 元素存储到 Google Firebase?
- ios - iOS StarScream,WebSocket 有时不会在应用程序前台重新连接
- python - 如何根据出现最少的列值删除行
- mpdf - 如果内容在 mpdf 中与页脚重叠,如何将页脚推到下一页?
- python - 使用 Python 连接到网络管理器(公司)VPN
- youtube-api - 在 YouTube 上获取热门新闻视频的 ID 时遇到问题?
- c# - 无法在单击按钮时获取数据网格回发值
- python - 用平均值替换异常值
- c++ - 无法进入 while 循环。它与使用无序地图有关吗?
- angular - 当我通过 Renderer2 在输入元素上添加 required 时,Angular 不会添加 ng-invalid