[Level 3]
Title: re
- One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
信息不足,同樣查看源碼,看到一堆字符串,且全是字母。根據提示,想到應該是兩組三個大寫字母夾著一個小寫字母,使用正則表達式匹配求解。找出第一個字母時修改url轉到的網頁顯示yes. but there are more.,需要找出所有符合條件的字母:
import re
pattern = re.compile('[a-z][A-Z]{3}[a-z][A-Z]{3}[a-z]')
target = ''
with open('re.txt',encoding='utf-8') as f:
s = f.read()#.replace('\n','')
match = pattern.search(s)
while(match):
temp = s[match.start():match.end()]
target += temp[4]
s = s[match.end()-1:]
match = pattern.search(s)
print(target)
或直接在源碼中讀取目標字符串:
import urllib.request
s = urllib.request.urlopen('http://www.pythonchallenge.com/pc/def/equality.html').read().decode('utf-8').replace('\n','')
s = re.findall('<!--(\w*)-->',s)[0]
運行得到linkedlist,修改url網頁提示linkedlist.php,即[Level 4]
小結
尋找到匹配的第一個字符后,再從該字符后三個字符(大寫字母)繼續開始匹配尋找。
-
re.compile(pattern, flags=0)
將正則表達式模式編譯成可被match()
和search()
方法調用的對象。 -
regex.search(string[, pos[, endpos]])
掃描string 尋找正則表達式產生匹配后的第一個位置 , 返回對應的 match object。 -
match.start([group])
和match.end([group])
返回由group匹配的子字符串的開頭和結尾的索引。 - search() and match()
Python Challenge Wiki
不用re的解法
import string
def level_3(t1):
pad = "xx"
t1 = pad + t1 + pad
markers = "".join([ '1' if c in string.ascii_uppercase else '0' for c in t1])
pattern = "011101110"
def f(res, t2, markers):
n = len(markers.partition(pattern)[0])
return f(res+t2[n+4], t2[n+4:], markers[n+4:]) if n != len(markers) else res
return f('', t1, markers)
這個也挺有趣的:
> ```python
>>> import string
>>> code = data.replace("\n", "")
>>> word =''
>>> for i in range(len(code) - 8):
... if [c for c in code[i:i+9] if c in string.ascii_lowercase] == [code[i], code[i+4], code[i+8]]:
... word += code[i+4]
...
>>> word
'linkedlist'
將大小寫字母全部轉為1和0達到使用正則表達式的效果。
-
str.partition(sep)
在分隔符首次出現位置拆分成三個子字符串,并返以元組形式返回。未找到返回分隔符本身和兩個空字符串組成的元組。
更優雅的使用re
>> import re >> ''.join(re.findall('(?:^|[^A-Z])[A-Z]{3}([a-z])[A-Z]{3}(?:[^A-Z]|$)',text))
1. `(?:...)`在正則中表示匹配的子字符串不能在匹配后提取或在模式中引用。更多語法查看[Regular Expression Syntax](https://docs.python.org/3/library/re.html#regular-expression-syntax)
2. [`re.findall(pattern, string, flags=0)`](https://docs.python.org/3/library/re.html?highlight=findall#re.findall)返回所有非重疊匹配的模式。如果模式中存在一個或多個組,則返回組列表;如果模式中組有嵌套(不知這樣理解對不),返回元組的列表。
####[More](http://wiki.pythonchallenge.com/index.php?title=Level3:Main_Page)