在我正在python中編寫的程序中,我希望所有格式化爲__word__
的單詞都能脫穎而出。我如何使用正則表達式來搜索這些單詞?創建Reg Exp來搜索__word__?
1
A
回答
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:']
1
採取這裏squizz:http://docs.python.org/library/re.html
這應該告訴你的語法和從中可以建立字(S)前和檢查的例子後掛起2個下劃線。
0
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__
相關問題
- 1. Reg Exp優化
- 2. javascript reg exp
- 3. Visual DataFlex Reg Exp
- 4. Bash reg-exp替換
- 5. 爲reg-exp創建一個預定義的集合。 (gsub,grepl,...)
- 6. Reg exp找到數字
- 7. 密碼驗證REG EXP
- 8. 用Reg-Exp解析類名
- 9. 的Javascript:更換REG EXP
- 10. 使用reg exp搜索並替換數據庫中存在的電子郵件ID exp
- 11. 搜索創建
- 12. 創建.reg文件
- 13. Javascript Reg括號中的Exp號碼
- 14. 的Java REG EXP匹配模式
- 15. Reg Exp:僅匹配數字和空格
- 16. 如何使用否定「?!」在grep reg exp
- 17. Python的REG EXP - 匹配號碼
- 18. 需要一點reg-exp幫助
- 19. 如何創建搜索欄來更新搜索輸入
- 20. Github搜索創建
- 21. 創建搜索欄
- 22. 創建一個方法來搜索數組索引重複值
- 23. 搜索和創建PHP
- 24. 創建快速搜索值
- 25. 搜索欄來搜索TextViews
- 26. 如何創建reg-expression來查找url文件擴展存在?
- 27. 只有REG存在創建txt文件
- 28. 如何在Java中創建reg ex
- 29. 輸入來創建平衡二叉搜索樹
- 30. PHP MySQL的創建查詢來搜索多個表
這一款適合我的需求。 – 2010-02-16 04:39:14
'\ S'將匹配任何非空格字符(包括符號),所以'.__ + __。'將匹配。 – Amarghosh 2010-02-16 04:43:03
@Amarghosh,OP沒有指定「單詞」的含義,所以我將它解釋爲一串非空白字符。當然你可以使用'\ w'而不是'\ S',但是像__Here's__這樣的詞會被打破 – 2010-02-16 04:46:48