正则表达式替换所有符号,排除 # 和 @。

huangapple go评论81阅读模式
英文:

Regexp replace all symbols excluding # and @

问题

我对使用正则表达式不是非常自信,但我的最终目标是创建一个能够删除除了@#之外的所有符号的表达式。

我现在有的是 [\\p{P}\\d]
它工作得很好,但它也会删除我需要保留的@#

这是我尝试改变的示例输入字符串:

^Hello, my #friend @Даниил%% 中英 字 典!!.

我想将其改为:

Hello my #friend @Даниил 中英 字 典
英文:

I am not super confident with using regexp, but my end goal is to have something that is removing all symbols excluding @ and #.

What I have now is [\\p{P}\\d].
It works fine but it also removes @ and # which I need to keep.

Here is the sample input string:

^Hello, my #friend @Даниил%% 中英 字 典!!.

that I am trying to change into

Hello my #friend @Даниил 中英 字 典

答案1

得分: 2

捕获您需要保留的符号,并使用$1反向引用替换,以在结果字符串中恢复捕获的部分:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	s := "^Hello, my #friend @Даниил%% 中英 字 典!!"
	re := regexp.MustCompile(`([#@])|[\p{P}\p{S}\d]`)
	s = re.ReplaceAllString(s, "$1")
	fmt.Println(s)
}

查看此Go演示,输出为Hello my #friend @Даниил 中英 字 典

请注意,^不属于\p{P}类别,因此我添加了\p{S}

模式为([#@])|[\p{P}\p{S}\d],请参见在线演示

详细信息

  • ([#@]) - 捕获组1(在替换模式中使用$1 / ${1}引用)匹配#@

  • | - 或

  • [\p{P}\p{S}\d] - 标点符号、符号或数字字符

英文:

Capture the symbols you need to keep and replace with $1 backreference to restore the captured part in the resulting string:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	s := "^Hello, my #friend @Даниил%% 中英 字 典!!."
	re := regexp.MustCompile(`([#@])|[\p{P}\p{S}\d]`)
	s = re.ReplaceAllString(s, "$1")
	fmt.Println(s)
}

See this Go demo printing Hello my #friend @Даниил 中英 字 典.

Note that ^ does not belong to the \p{P} category, thus, I added \p{S} one.

The pattern is ([#@])|[\p{P}\p{S}\d], see its online demo.

Details:

  • ([#@]) - Capturing group 1 (referred to with $1 / ${1} from the replacement pattern) matching a # or @
  • | - or
  • [\p{P}\p{S}\d] - a punctuation, symbol or digit char.

huangapple
  • 本文由 发表于 2017年6月6日 09:25:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/44380031.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定