我对使用正则表达式并不是很有信心,但我的最终目标是删除除 @
和 #
之外的所有符号。
我现在拥有的是[\\p{P}\\d]
。
它工作正常,但它也删除了我需要保留的 @
和 #
。
这是示例输入字符串:
^Hello, my #friend @Даниил%% 中英 字 典!!.
我正在努力改变
Hello my #friend @Даниил 中英 字 典
最佳答案
捕获需要保留的符号并用 $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)
}
参见this Go demo打印 Hello my #friend @Даниил 中英字典
.
请注意,^
不属于\p{P}
类别,因此,我添加了\p{S}
类别。
模式为([#@])|[\p{P}\p{S}\d]
,参见its online demo .
详细信息:
([#@])
- 捕获组 1(通过替换模式中的$1
/${1}
引用)匹配#
或@
|
- 或[\p{P}\p{S}\d]
- 标点符号、符号或数字字符。
关于正则表达式替换除#和@之外的所有符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380031/