You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby正则移除文本特殊字符产生多余空白/单词合并如何修复

问题场景

现有一段混入乱码特殊字符的英文文本,原始内容如下:

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,同时保留文本原有的正常空格、标点格式,不破坏整体可读性。

已测试两种正则方案均未达到预期:

  • 方案1:执行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 "

缺陷:原乱码位置生成多个连续空白,原有标点位置也出现多余空格,格式不符合要求。

  • 方案2:执行text.gsub!(/[^a-zA-Z0-9]/,""),直接删除所有非字母数字字符,返回结果:
PleasereviewtheentiretyofthisreporttoconfirmthatthedetailsofthereportareoftherequestedpatientThisinformationshallonlybeusedforthepurposeofprovidingmedicalorpharmaceuticaltreatmenttoabonafidecurrentpatientThisinformationshallnotbeprovidedtoanyotherpersonorentityexceptbyorderofacourtofcompetentjurisdiction

缺陷:词与词之间的正常空格被全部删除,所有单词拼接为连续长文本,无法正常阅读。

可行方案

调整正则白名单规则,仅删除明确属于乱码的字符,保留所有正常需要的内容即可:

# 第一步:删除白名单外的乱码,白名单包含大小写英文字母、数字、空白字符、常规英文标点
text.gsub!(/[^a-zA-Z0-9\s.,'";:!?()\-]/, '')
# 可选操作:如果处理后存在少量连续空格,执行归一化替换为单个空格
text.gsub!(/\s+/, ' ')

执行上述代码后,乱码字符会被直接清除,原本被乱码分隔的detai和ls会自动拼接为正确的details,文本原有的空格、标点都会完整保留,不会出现多余空格或单词粘连问题。
如果文本中还有其他需要保留的合法特殊字符,直接将对应字符补充到第一步正则的白名单(方括号内的规则)中即可。

内容的提问来源于stack exchange,提问作者Pouya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 22:48:18