2010-02-16 42 views

回答

4

也許類似

\b__(\S+)__\b 

>>> import re 
>>> re.findall(r"\b__(\S+)__\b","Here __is__ a __test__ sentence") 
['is', 'test']  
>>> re.findall(r"\b__(\S+)__\b","__Here__ is a test __sentence__") 
['Here', 'sentence'] 
>>> re.findall(r"\b__(\S+)__\b","__Here's__ a test __sentence__") 
["Here's", 'sentence'] 

或者你可以在這個詞的周圍放置標籤

>>> print re.sub(r"\b(__)(\S+)(__)\b",r"<b>\2<\\b>","__Here__ is a test __sentence__") 
<b>Here<\b> is a test <b>sentence<\b> 

如果您需要在法律的單詞字符更爲精細的控制,最好是明確

\b__([a-zA-Z0-9_':])__\b ### count "'" and ":" as part of words 

>>> re.findall(r"\b__([a-zA-Z0-9_']+)__\b","__Here's__ a test __sentence:__") 
["Here's"] 
>>> re.findall(r"\b__([a-zA-Z0-9_':]+)__\b","__Here's__ a test __sentence:__") 
["Here's", 'sentence:'] 
+0

這一款適合我的需求。 – 2010-02-16 04:39:14

+0

'\ S'將匹配任何非空格字符(包括符號),所以'.__ + __。'將匹配。 – Amarghosh 2010-02-16 04:43:03

+1

@Amarghosh,OP沒有指定「單詞」的含義,所以我將它解釋爲一串非空白字符。當然你可以使用'\ w'而不是'\ S',但是像__Here's__這樣的詞會被打破 – 2010-02-16 04:46:48

0

這個最簡單的正則表達式將是

__.+__ 


如果你想從你的代碼訪問這個詞本身,就應該使用

__(.+)__ 
+2

這聽起來太貪婪 – 2010-02-16 04:39:49

+0

'__ __'也許 – bernie 2010-02-16 05:05:22

+0

丹尼爾(+) - 對'你好__world__讓吃__pizza__',您正則表達式將捕獲'__world__讓吃__pizza__'。 – Kobi 2010-02-16 05:35:12

0

這會給你所有這些單詞的列表

>>> import re 
>>> m = re.findall("(__\w+__)", "What __word__ you search __for__") 
>>> print m 
['__word__', '__for__'] 
0
\b(__\w+__)\b 

\b字界
\w+個一個或多個字符 - [a-zA-Z0-9_]

0

簡單字符串函數。沒有正則表達式

>>> mystring="blah __word__ blah __word2__" 
>>> for item in mystring.split(): 
...  if item.startswith("__") and item.endswith("__"): 
...  print item 
... 
__word__ 
__word2__