Joh*_*ohn 24 python regex string
我有这个代码从正则表达式字符串中删除所有标点符号:
import regex as re
re.sub(ur"\p{P}+", "", txt)
Run Code Online (Sandbox Code Playgroud)
如何更改它以允许连字符?如果你能解释一下你是如何做到的,那就太好了.我明白在这里,如果我错了,请纠正我,在标点后加上任何东西.
Kob*_*obi 23
[^\P{P}-]+
Run Code Online (Sandbox Code Playgroud)
\P是\p- 不是标点符号的补充.所以这匹配任何不是(不是标点符号或破折号)的东西 - 导致除破折号之外的所有标点符号.
示例:http://www.rubular.com/r/JsdNM3nFJ3
如果你想要一种非复杂的方式,另一种方法是\p{P}(?<!-):匹配所有标点符号,然后检查它不是破折号(使用负面的lookbehind).
工作示例:http://www.rubular.com/r/5G62iSYTdk
Gal*_*ong 15
以下是如何使用re模块进行操作,以防您必须坚持使用标准库:
# works in python 2 and 3
import re
import string
remove = string.punctuation
remove = remove.replace("-", "") # don't remove hyphens
pattern = r"[{}]".format(remove) # create the pattern
txt = ")*^%{}[]thi's - is - @@#!a !%%!!%- test."
re.sub(pattern, "", txt)
# >>> 'this - is - a - test'
Run Code Online (Sandbox Code Playgroud)
如果性能很重要,您可能想要使用str.translate,因为它比使用正则表达式更快.在Python 3中,代码是txt.translate({ord(char): None for char in remove}).