2014-01-18 65 views
15

我有這樣的代碼從一個正則表達式字符串,刪除所有標點符號:Python的正則表達式,刪除所有的標點,除了連字符unicode字符串

import regex as re  
re.sub(ur"\p{P}+", "", txt) 

我將如何改變它允許連字符?如果你能解釋你是如何做到的,那就太好了。我明白,在這裏,如果我錯了,請糾正我,在標點符號後加上P。

+3

@Jerry - 我看了一下,發現這個:http://stackoverflow.com/a/4316097/7586 - 這是'regex',而不是're'。我猜他們有兩個。 – Kobi

+0

@Kobi哦...我想這可以解釋它。 – Jerry

回答

18
[^\P{P}-]+ 

\P\p互補 - 沒有標點符號。所以這匹配任何而不是(不是標點符號或短劃線) - 導致除破折號外的所有標點符號。

例子:http://www.rubular.com/r/JsdNM3nFJ3

如果你想有一個非迂迴的方式,另一種是\p{P}(?<!-):匹配所有的標點,然後再檢查,這不是一個破折號(使用負回顧後)。
工作例如:http://www.rubular.com/r/5G62iSYTdk

+1

太好了,謝謝。怎麼排除多個?如 '。'以及。 – John

+1

@Anonymous - 第一個是'[^ \ P {P} \ - 。] +',第二個'\ p {P}(?<![\ - 。])'。非常簡單。 – Kobi

+0

爲什麼現在{P}之後有'\'而不是第一個? – John

0

您既可以指定要手動刪除,如[._,]或提供的功能,而不是替換字符串標點符號:

re.sub(r"\p{P}", lambda m: "-" if m.group(0) == "-" else "", text) 
6

以下是如何與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' 

如果性能問題,您可能需要使用str.translate,因爲it's faster than using a regex。在Python 3中,代碼是txt.translate({ord(char): None for char in remove})

+1

're'在這裏指的是[this module](https://pypi.python.org/pypi/regex),它有'\ p'。 –

相關問題