代码之家  ›  专栏  ›  技术社区  ›  dragonfly02

删除双单引号,但不删除单引号

  •  0
  • dragonfly02  · 技术社区  · 7 年前

    如何在Ruby中删除字符串中的双引号而不是单引号?例如从 That's 'large' ,至 That's large .

    0 回复  |  直到 7 年前
        1
  •  4
  •   Gurmanjot Singh    7 年前

    试试这个正则表达式:

    \B'((?:(?!'\B)[\s\S])*)'
    

    将每个匹配项替换为 \1

    Click for Demo

    代码( Result

    re = /\B'((?:(?!'\B)[\s\S])*)'/m
    str = 'That\'s \'large\'
    The 69\'ers\' drummer won\'t like this.
    He said, \'it\'s clear this does not work\'. It does not fit the \'contractual obligations\''
    subst = '\\1'
    
    result = str.gsub(re, subst)
    
    # Print the result of the substitution
    puts result
    

    说明:

    • \B
    • ((?:(?!'\B)[\s\S])*) -匹配0+个出现的任何字符 [\s\S] 哪个(不以开头) ' 后跟非单词边界)。这是在第1组中捕获的。
    • -匹配a
        2
  •  2
  •   Schwern    7 年前

    这是一个像解析XML或HTML这样的泥潭,不能用regex来完成,但是你可以假装它基本上可以工作。你可以调整它永远不会得到正确的。

    你可以寻找平衡的引号,也就是成对的引号,但这没有帮助。是 That's 'large' 被剥离为 Thats large' That's large

    相反,你需要给它一个英语语法的理解,当 ' apostrophe 对一个报价。一些简单的东西,知道收缩和所有格的基本知识。收缩: don't won't I'll . 所有格: Joe's s' . 也许你可以敲一个正则表达式跳过这些。

    但很快就会变得复杂起来。 KO'd fo'c's'le . 或者某人的名字 O'Doole .

    可以 It's clear he said, 'this isn't a contraction'. 匹配前面的报价 this contraction 可能是安全的。

    # Use negative look behind and ahead to look for quotes which are
    # not after and before a word character.
    # Use a non-greedy match to catch multiple pairs of quotes.
    re = /(?<!\w)'(.*?)'(?!\w)/
    sentence.gsub(re, '\1')
    

    这在很多情况下都有效。

    That's 'large' -> That's large
    Eat at Joe's -> Eat at Joe's
    I'll be Jane's -> I'll be Jane's
    Jones' three cats' toys. -> Jones' three cats' toys.
    It's clear he said, 'this isn't a contraction'. -> It's clear he said, this isn't a contraction.
    'scare quotes' -> scare quotes
    The 69'ers' drummer -> The 69'ers' drummer
    Was She's success greater, or King Solomon's Mines's? -> Was She's success greater, or King Solomon's Mines's?
    The 69'er's drummer and their 'contractual obligations'. -> The 69'er's drummer and their contractual obligations.
    He said, 'it's clear this doesn't work'. -> He said, it's clear this doesn't work.
    

    但不总是这样。

    His 'n' Hers's first track is called 'Joyriders'. -> His n Hers's first track is called Joyriders.
    

        3
  •  0
  •   James Hibbard    7 年前

    如果单引号仅出现在单词字符(即A-z、A-z、0-9或下划线字符)周围,则会有轻微的变化。您可以使用:

    phrase = "That's 'large' and not 'small', but it's still 'amazing'."
    phrase.gsub(/'(\w*)'/, '\1')
    => "That's large and not small, but it's still amazing."
    

    推荐文章