【问题标题】:Remove all punctuation except in numbers删除除数字以外的所有标点符号
【发布时间】:2020-06-12 11:40:37
【问题描述】:

我有像I want to buy 2 kg of apples! 这样的字符串,我想从这些句子中删除某些标点符号,到目前为止,这已经足够了:

text = strings.ReplaceAll(text, ".", "")
text = strings.ReplaceAll(text, ",", "")
text = strings.ReplaceAll(text, "?", "")
text = strings.ReplaceAll(text, "!", "")

但是当句子中包含2.5 kgapples 时,它会变成25 kg。因此,如何删除标点符号但保留数字中使用的标点符号?我的想法是手动迭代所有字符,但我觉得必须有一个更有效的解决方案。

【问题讨论】:

标签: go


【解决方案1】:

您可以使用regexp 首先查找所有带有周围字符的标点符号,然后确定匹配的部分是浮点数(例如2.5)还是标点符号。对标点符号执行替换并保留浮动。

例子:

package main

import (
  "fmt"
  "regexp"
  "strings"
)

func main() {
  text := "I want. to, buy 2.5 kg of apples!"

  // Regexp that finds all puncuation characters grouping the characters that wrap it
  re := regexp.MustCompile(`(.{0,1})([^\w\s])(.{0,1})`)

  // Regexp that determines if a given string is wrapped by digit characters
  isFloat := regexp.MustCompile(`\d([^\w\s])\d`)

  // Get the parts using the punctuation regexp... e.g. "t. "
  parts := re.FindAllString(text, -1);


  // Iterate through the parts
  for _, part := range parts {
    // Determine if the part is a float...
    isAFloat := isFloat.MatchString(part)
    // If it is not a float, make a single replacement to remove the puncuation
    if !isAFloat {
      newPart := re.ReplaceAllString(part, "$1$3")
      text = strings.Replace(text, part, newPart, 1)
    }
  }
  // prints: "I want to buy 2.5 kg of apples"
  fmt.Println(text)
}

Go Playground

根据您期望的字符串,您可能需要在操作后的字符串上将其作为函数运行几次,直到没有发生任何更改,例如如果字符串是“我不会完全替换...”。

【讨论】:

  • 我对我的答案进行了编辑,以实际进行正确的替换。但不确定性能。
猜你喜欢
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-26
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多