R语言多行文本列替换行首字符:为何^o正则表达式不生效?
^o 匹配不到行首的"o "? 问题背景
我需要把下面文本里所有行首的o 替换成• :
• Direct the Department’s technical
• Perform supervisory and managerial responsibilities as leader of the program
o Set direction to ensure goals and objectives
o Select management and other key personnel
o Collaborate with executive colleagues to develop and execute corporate initiatives and department strategy
o Oversee the preparation and execution of department’s Annual Financial Plan and budget
o Manage merit pay
• Perform other duties as assigned
试了三段R代码:
test<- sub(test, pattern = "o ", replacement = "• ") # 没用(只替换第一个匹配项,还没限定行首) test<- gsub(test, pattern = "^o ", replacement = "• ") # 也没用 test<- gsub(test, pattern = "o ", replacement = "• ") # 能替换但会把"to"改成"t•"
问题根源
R里的正则默认规则是:^只匹配整个字符串的开头,不是每一行的开头。你的文本是一个包含多行的字符串,那些行首的o 都是换行之后的行开头,不是整个字符串的起始位置,所以^o 根本碰不到这些位置,自然替换失败。
解决办法
要让^匹配每一行的开头,得开多行模式,在R里只要在正则开头加(?m)就行:
test <- gsub(test, pattern = "(?m)^o ", replacement = "• ")
这样就只会替换每行开头的o ,不会误伤文本中间的"o"了。
内容的提问来源于stack exchange,提问作者user3482393

