2015-05-08 161 views
1

試圖在Python中編寫正則表達式來匹配字符串。Python正則表達式

我想匹配的開始爲firstfirst?21313但不first.

所以基本上,我不想匹配任何有.期間字符輸入。我試過word.startswith(('first[^.]?+'))但這不起作用。我也試過word.startswith(('first.?+')),但那也沒有奏效。這裏漂亮難倒

+0

不要讓'[^]'可選的''? – Barmar

+0

'str.startswith()'需要文字 - 不是正則表達式...查看導入並使用實際的're'和'.match'方法... –

回答

1
import re 
def check(word): 
     regexp = re.compile('^first([^\..])+$') 
     return regexp.match(word) 

如果你不想點: ^第一([^ ...])+ $ (第一+ allcharacter除了點和第一個不能是單獨的)。

+0

如何用'startswith'做到這一點?當我嘗試時,它給了我什麼問題? – simplycoding

+0

爲什麼你想用startswith?做,如果你有很多檢查,並且你只想在一行中做,你可以創建如下方法:check(word,regexpParam)和re.compile(refexpParam),然後你改變:word.startswith(('first [^。]?+'))for check(word,'^ first([^ \ ..])+ $') – idelcano

0

你真的不需要這個正則表達式。

word.startswith('first') and word.find('.') == -1 

但如果你真的想利用正則表達式路線:

>>> import re 
>>> re.match(r'first[^.]*$', 'first') 
<_sre.SRE_Match object; span=(0, 5), match='first'> 
>>> re.match(r'first[^.]*$', 'first.') is None 
True 
+0

有很多邊緣情況和允許值, first.stuffafter'是一個。所以這肯定不會工作編輯:沒有及時看到你的編輯。看起來像另一個答案,我會嘗試測試 – simplycoding

+0

@simplycoding你從'first.stuffafter'期待什麼輸出?你期望以['first','stuffafter']的形式出現一個列表嗎?您是否期望來自包含文本的匹配的兩個捕獲組? – Shashank