2015-05-11 158 views
0

我要檢查,如果一個字符串在Python 3檢查一個字符串是在python

例如正則表達式匹配完全正則表達式表達一個完整的比賽,如果我有:

regex = "(A*B)*" 
stringone = "AABAABB" 
stringtwo = "ABCAAB" 
  • stringone將是正則表達式的匹配,
  • stringtwo不會匹配。

我試過使用內置的重新模塊,但不管我做了什麼,我總是收到沒有類型的對象。

這是我的代碼

compiled_regex = re.compile(regex) 
if compiled_regex.match(string).group(0) == string: 
    print("Match") 

回答

3

您可以添加行(^)和行末($)模式,開始新的正則表達式:

regex = r"^(A*B)*$" 

pattern = re.compile(regex) 
for s in "AABAABB", "ABCAAB", "B", "BBB", "AABAABBx", "xAABAABB": 
    if pattern.match(s): 
     print "Matched:", s 

此輸出:

 
Matched: AABAABB 
Matched: B 
Matched: BBB 

或者您也可以使用您的正則表達式與匹配對象,但使用group(),而不是groups()

pattern = re.compile(r'(A*B)*') 
for s in "AABAABB", "ABCAAB", "B", "BBB", "AABAABBx", "xAABAABB": 
    m = pattern.match(s) 
    if m is not None and m.group() == s: 
     print "Matched:", s 

輸出:

 
Matched: AABAABB 
Matched: B 
Matched: BBB 
1

你的正則表達式工作正常,看:

import re 

regex = "(A*B)*" 
stringone = "AABAABB" 
stringtwo = "ABCAAB" 

compiled_regex = re.compile(regex) 
if compiled_regex.match(stringone): 
    print("Match") 
    print(compiled_regex.match(stringone)) 

輸出:

Match                                                                           
<_sre.SRE_Match object; span=(0, 7), match='AABAABB'> 

如果你想額外檢查字符串不包含除正則表達式指定的內容之外的任何內容,您應該使用^$,像這樣:

regex = "^(A*B)*$" 
+0

但是如果我更換stringtwo它仍然會打印比賽,我不希望它做的stringone,我希望有一個完整的比賽。 – JeLLyB0x3r

+0

@ JeLLyB0x3r是的,因爲它是匹配的。要獲得完整的匹配,您應該使用開始和結束標記,請參閱我的編輯 – SanD

相關問題