用正则表达式区分大小写的断字

时间:2019-06-19 15:38:02

标签: r regex-group backreference

我正在尝试用德语输入清理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 package(v0.3.0)于2019-06-19创建

有人知道如何使整个正则表达式区分大小写,以致在第二种情况下(即每次在破折号和空格后出现und单词时都不会触发它)吗?

1 个答案:

答案 0 :(得分:2)

也许您可以使用否定或肯定的前瞻功能(例如,参见Regex lookahead, lookbehind and 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 package(v0.3.0)于2019-06-19创建