如何用' \\ W&#39 ;?替换字符串中的所有标点符号?

时间:2017-06-21 03:19:49

标签: r regex

def createTypeTag(tp: String): TypeTag[_] = {
  val typs = // ... manipulate the string to extract type and parameters
  val typSym = currentMirror.staticClass(typs[0])
  val paramSym = currentMirror.staticClass(typs[1])

  val tpe = universe.internal.typeRef(NoPrefix, typSym, List(paramSym.selfType))

  val ttag = TypeTag(currentMirror, new TypeCreator {
    override def apply[U <: Universe with Singleton](m: Mirror[U]): U#Type = {
      assert(m == currentMirror, s"TypeTag[$tpe] defined in $currentMirror cannot be migrated to $m.")
      tpe.asInstanceOf[U#Type]
    }
  })
}

我想要实现的目标:

string = 'Hello, how are you?'

我做过的事:用&#39; \\ W&#39;

替换所有不是字母数字的字符
Hello\\W how are you\\W

我不太清楚为什么句号末尾的问号不是用&#39; \\ W&#39;并且为什么第一个空格被替换。任何人都可以帮我解决这个问题吗?谢谢!

1 个答案:

答案 0 :(得分:2)

我们可以做到

gsub("[,?]", "\\\\W", string)
#[1] "Hello\\W how are you\\W"

如果还有其他字符,请使用[[:punct:]]

gsub("[[:punct:]]", "\\\\W", string)
#[1] "Hello\\W how are you\\W"