繁体   English   中英

在Python正则表达式matchobj中,如何进行子字符串匹配,并将匹配项分配给变量?

[英]in a Python regex matchobj, how to do a substring match, and assign the match to a variable?

有了这个re.sub和'replace'功能-谢谢Ignacio的指导! -我可以用字符串' * NONSENSE * '替换很长的文本blob中的所有匹配项-到目前为止,太好了!

在此过程中,我想在matchobj中找到子字符串 ,将其称为“ findkey ”,因此我可以对其进行其他工作...

怎么办呢?

data = re.sub('(:::[A-Z,a-z,:]+:::)', replace, data)

def replace(matchobj):
 if matchobj.group(0) != '':

  # this seems to work:
  tag = matchobj.group(1)

  # but this doesn't:
  findkey = re.search(':::([A-Z,a-z]+):::', tag)

  return '********************  NONSENSE  ********************'

 else:
  return ''

你在找吗

findkey = re.search(':::([A-Z,a-z]+):::', tag).group()

请注意group(), 此文档也可以提供帮助。

尝试这个。 您可以将内部匹配为初始子调用的一部分。

import re

data = ":::::::::::BLAH:::::::::, ::::::::MORE:::::::"

def replace(matchobj):
  # this seems to work:
  tag = matchobj.group(0)
  findkey = matchobj.group(1)

  print findkey

  return '********************  NONSENSE  ********************'


data = re.sub(r':::(?P<inner>[A-Z,a-z]+):::', replace, data)

print data

返回以下内容

BLAH
MORE
::::::::********************  NONSENSE  ********************::::::, :::::********************  NONSENSE  ********************::::

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM