2017-01-27 89 views
0

例如,如果我的代碼:將通配符整數放入字符串最簡單的方法是什麼?

for row in self.reader: 
    if row: 
     if row[0] == "Stage * Disk Face": 
      """CODE TO EXECUTE""" 

然而,有沒有一種方法,使星號*任意號碼,這樣,如果找到字符串"Stage 1 Disk Face""Stage 2 Disk Face""Stage 3 Disk Face"等,代碼將執行?原因並不是每個階段號碼都會有磁盤面部特徵。我基本上需要找出是否至少有一個,任意數字。

+4

我將在一行中使用正則表達式[ 0]。如果是這樣,你可以使用「\ d +」作爲'通配符' – MaLiN2223

回答

4

這應該工作:

import re 

for row in self.reader: 
    if row: 
     if re.match('^Stage [0-9]+ Disk Face$', row[0]): 
      """CODE TO EXECUTE""" 
+0

它不會抓住x> 9的「Stage x Disk Face」。我會建議在開始時使用「[0-9] +」 – MaLiN2223

+0

''' $'在末尾 –

+0

全部都是真的,只是編輯:) – zipa

0

入住這

# coding=utf8 
# the above tag defines encoding for this document and is for Python 2.x compatibility 

import re 

regex = r"(Stage)[0-9](Disk Face)" 

test_str = "Stage 1 Disk Face" 

matches = re.search(regex, test_str) 

if matches: 
    print ("Match was found at {start}-{end}: {match}".format(start = matches.start(), end = matches.end(), match = matches.group())) 

    for groupNum in range(0, len(matches.groups())): 
     groupNum = groupNum + 1 

     print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum))) 

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitutio 
0
import re 

#if row[0] == "Stage * Disk Face": 
if re.search(r'Stage \d Disk Face', row[0]): 
    pass 
0

這將是最簡單的只是使用正則表達式:

import re 

rows = [["Stage 1 Disk Face"], ["Stage 2 Disk Face"], ["Stage 3 Disk Face"]] 
pattern = re.compile("Stage .* Disk Face") 

for row in rows: 
    if row: 
     if pattern.match(row[0]): 
      print(row[0]) 
相關問題