Python中有一种很好的方法:
基本上我想要一种简单的方法来输入简单的解析器/扫描器语法,并简单地提取某个结构中的所有匹配(例如元组)
假设我们在String中编码了国家代码,城市名称和索引。我们想提取这个:
input = "123-NEWYORK-[2]"
grammar = "<country,[0-9]+>-<city,[A-Z]*>-[<index,[0-9]*>"
res = HOW_TO_DO_THIS(input,grammar)
if res is None:
print("Does not match")
else
(countrycode,city,index) = res
答案 0 :(得分:2)
使用python3,你可以注意到正在修改正则表达式:
import re
input = "123-NEWYORK-[2]"
grammar = r"(?P<country>[0-9]+)-(?P<city>[A-Z]*)-(?P<index>\[[0-9]*\])"
res = re.findall(grammar, input)
if not res:
print("Does not match")
else:
(countrycode,city,index) = res[0]
print(countrycode)
修改:
re.findall(patter, input_string)
。不是相反。if not x
比if x is None
答案 1 :(得分:0)
查看此代码。这仅适用于简单的文本查找,但您可以根据您的方案进行扩展
import re
f=open('sample.txt',"w")
f.write("<p class = m>babygameover</p>")
f.close()
f=open('sample.txt','r')
string = "<p class = m>(.+?)</p>" # regular expression
pattern = re.compile(string) # compiling
text = f.read()
search = re.findall(pattern,text) # searching
print search