2014-09-28 71 views
0

我有一個單一參數的函數,它是一個包含重音字符的unicode字符串。我想在該字符串中找到一個或多個模式並將其打印出來。Python 2.7正確的語法重新匹配Unicode字符串中的重音字符?

我不知道如何正確地格式化模式,或者正確使用re.match與unicode,或者使用unicode提取match.groups()。使用ASCII更容易。哎呀。

的Python 2.7

sentence = "These characters, ÄÜ, are special." 

def findInSentence(sentence): 

    pattern = re.compile("ÄÜ", re.UNICODE) 
    return re.match(sentence, pattern).groups() 

回答

1

有正確使用若干問題的Unicode:

  1. 聲明源文件的編碼。
  2. 將文件保存在聲明的編碼中。
  3. 使用Unicode字符串。

另外,正確使用re.search作爲@ M42指出。

在您的搜索模式中也沒有groups(),因此如果存在匹配,請使用.group(0)打印匹配項。

注意re.UNICODE沒有在這種情況下必要的,因爲它不僅影響如何的特殊匹配序列\w\W\b\B\d\D\s\S工作,他們沒有被使用。

# coding: utf-8 
import re 

sentence = u"These characters, ÄÜ, are special." 

def findInSentence(sentence): 
    pattern = re.compile(u"ÄÜ", re.UNICODE) 
    return re.search(pattern, sentence).group(0) 

print findInSentence(sentence) 

輸出:

ÄÜ 
1

使用re.search而不是re.match

re.match被錨定在字符串的開頭,並且re.search搜索整個字符串。

的語法searchmatch是:

re.search(pattern, string, flags=0) 
re.match(pattern, string, flags=0) 

你倒的模式和字符串。

+0

這是行不通的。我無法編碼字符串或使用重新。功能不會出錯。 – 2014-09-28 09:10:23

+0

@ user1473511:交換模式和字符串,請參閱我的編輯。 – Toto 2014-09-28 09:16:31

+0

sentence =「這些字符,」很特別。「 該行引發錯誤。 – 2014-09-28 09:22:53