首页 > 解决方案 > 使用正则表达式替换区分大小写的断字

问题描述

我正在尝试用德语输入清理 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出现在破折号和空格之后?

标签: rregex-groupbackreference

解决方案


也许您可以使用负或正前瞻(参见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 日创建


推荐阅读