2015-05-08 160 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