【问题标题】:Elegant way of extracting substrings matching regex?提取匹配正则表达式的子字符串的优雅方法?
【发布时间】:2017-09-15 12:21:41
【问题描述】:

在 Python 中有什么好的方法吗:

  • 检查字符串是否匹配一组正则表达式
  • 如果是:将匹配的部分作为元组返回。

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

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

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

【问题讨论】:

标签: python regex compiler-construction regex-greedy bnf


【解决方案1】:

用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 更容易(也更通用)

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • 这不是我要找的。 findall 正在查找所有出现的 1 个正则表达式。我希望所有出现的子正则表达式都根据某个更大的正则表达式放置(所以在上面的例子中 -[].
    • @robert 您可以逐行读取数据并循环执行您的工作
    猜你喜欢
    • 2020-12-15
    • 2022-07-11
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 2013-04-13
    相关资源
    最近更新 更多