【问题标题】:Which regex removes punctuation from quotation marks in text哪个正则表达式从文本中的引号中删除标点符号
【发布时间】:2019-08-01 22:51:27
【问题描述】:

我有一个数据库,并且在整个文本中有一些引号中的引号。我想删除所有的点“。”在文本中用引号括起来。

我的代码用引号标出文本,但如果有多个引号或多个点,则仅删除第一个。

# Simple phrase:
string <- '"é preciso olhar para o futuro. vou atuar" no front '

# Code that works for a simple 1-point sentence:
str_replace_all(string, '(\".*)\\.(.*\")','\\1\\2')

# Sentence with more than one point and more than one quote:
string <- '"é preciso olhar para o futuro. vou atuar" no front em que posso 
fazer alguma coisa "para .frente", disse jose.'

# it doesn't work as i would like
str_replace_all(string, '(\".*)\\.(.*\")','\\1\\2')

我希望引号中的所有点都被删除,但是您可以从示例中看到我开发的正则表达式不适用于更一般的情况。

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    您可以简单地将str_replace_all"[^"]*" 模式一起使用,并使用回调函数作为替换参数,通过gsub 调用删除所有点:

    str_replace_all(string, '"[^"]*"', function(x) gsub(".", "", x, fixed=TRUE))
    

    所以,

    • "[^"]*" 匹配 string 中以 " 开头的所有子字符串,然后是 " 以外的 0+ 个字符,然后是 "
    • 一旦找到匹配项,它就会作为x 传递给回调,其中gsub(".", "", x, fixed=TRUE) 用空字符串替换所有.fixed=TRUE 使其成为文字点,而不是正则表达式模式)。李>

    【讨论】:

    • 哇,function (x) 中的 replacement 参数是诀窍!
    【解决方案2】:
    mystring <-'"é preciso olhar para o futuro. vou atuar" no front em que posso 
    fazer alguma coisa "para .frente", disse jose.'
    

    您可以将以下patterngsub 一起使用:

    gsub('(?!(([^"]*"){2})*[^"]*$)\\.', "", mystring, perl = T)
    

    stringr相同:

    str_replace_all(mystring, '(?!(([^"]*"){2})*[^"]*$)\\.', '')
    

    输出:

    #> "é preciso olhar para o futuro vou atuar" no front em que posso 
    #> fazer alguma coisa "para frente", disse jose.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-25
      • 2013-08-27
      相关资源
      最近更新 更多