提取匹配正则表达式的子字符串的优雅方式?

Elegant way of extracting substrings matching regex?

Python有什么好的方法可以做到:

所以基本上我想要一种简单的方法来输入简单的 parser/scanner 语法,并简单地提取特定结构(例如元组)中的所有匹配项

假设我们在字符串中编码了国家代码、城市名称和索引。我们要提取这个:

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

查看此代码。这仅用于简单的文本查找,但您可以根据您的情况进行扩展

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

用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)

修改:

  • 正确的正则表达式是 (?P[0-9]+)-(?P[A-Z])-(?P[[0-9]])
  • python 中正则表达式模块的语法是 re.findall(patter, input_string)。不是相反。
  • if not xif x is None
  • 更容易(也更通用)