【问题标题】:Removing special characters from a sentence creates white spaces. How to fix?从句子中删除特殊字符会创建空格。怎么修?
【发布时间】:2022-07-01 01:18:45
【问题描述】:

我有一个包含特殊字符或符号的句子需要删除。这是句子:

text="Please review the entirety of this report to confirm that the detaiÒ‰ÏÎÇ◊ls of the report are of the requested patient. This information shall only be used for the purpose of providing medical or pharmaceutical treatment to a bona fide current patient. This information shall not be provided to any other person or entity except by order of a court of competent jurisdiction."

目的是删除“detaiÒ‰ÏÎÇ◊ls”中的这些字符并返回“details”。当我尝试运行这个正则表达式时: text.gsub!(/[^a-zA-Z0-9]/," ") 它返回了这个:

] pry(#<Role>)> text.gsub!(/[^a-zA-Z0-9]/," ")
=> "Please review the entirety of this report to confirm that the detai      ls of the report are of the requested patient  This information shall only be used for the purpose of providing medical or pharmaceutical treatment to a bona fide current patient  This information shall not be provided to any other person or entity except by order of a court of competent jurisdiction "

当我尝试删除像 text.gsub!(/[^a-zA-Z0-9]/,"") 这样的空格时,它返回了这个并合并了所有单词

PleasereviewtheentiretyofthisreporttoconfirmthatthedetailsofthereportareoftherequestedpatientThisinformationshallonlybeusedforthepurposeofprovidingmedicalorpharmaceuticaltreatmenttoabonafidecurrentpatientThisinformationshallnotbeprovidedtoanyotherpersonorentityexceptbyorderofacourtofcompetentjurisdiction

有没有人有更好的方法来解决这个问题?

【问题讨论】:

    标签: ruby-on-rails regex qregularexpression


    【解决方案1】:

    在您的第二次尝试中替换为空字符串。但也要在不应替换的字符列表中包含空格,因此它不会删除单词之间的空格。

    text.gsub!(/[^a-zA-Z0-9 ]/,"")
    

    【讨论】:

      【解决方案2】:

      您匹配此处未排除的每个 CHARACTER:[^a-zA-Z0-9]。

      1. 定义允许的字长,如 ([^a-zA-Z0-9]{1,}),它会起作用。
      2. 将“”改为“”

      https://regex101.com/r/8e7crO/1

      【讨论】:

        猜你喜欢
        • 2020-08-07
        • 2021-10-16
        • 2014-08-17
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-13
        相关资源
        最近更新 更多