简体   繁体   English

在Python中提取正则表达式匹配项的正确方法是什么?

[英]What's the correct way to extract a regexp match in Python?

I have found two ways to extract matches in Python: 我发现了两种在Python中提取匹配项的方法:

1. 1。

def extract_matches(regexp, text):
  matches = re.match(regexp, text)
  if matches:
    return matches.group(1)

2. 2。

def extract_matches(regexp, text):
  try:
    return re.findall(regexp, text)[0]
  except IndexError:
    return None

Which one would you suggest me to use? 您建议我使用哪一个? And do you know any other ways to do this? 您知道其他方法吗?

Thanks, Boda Cydo. 谢谢,博达·西多(Boda Cydo)。

I would more often use re.search (which returns any match, not just one constrained to start at the beginning of the string as re.match does!) if I'm looking for just one match, re.finditer if I want to loop over all matches. 如果我只想查找一个匹配项,则我会更经常使用re.search (它返回任何匹配项,而不是像re.match一样受约束地开始于字符串的开头!),如果我只想查找一个匹配项,则我想使用re.finditer循环所有比赛。 Never re.findall if I'm going after only one match though, that's wasted effort with no upside! 如果我只参加一场比赛, re.findall ,那是浪费精力,没有上升空间!

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

相关问题 导入python包的正确方法是什么? - What's the correct way to import a python package? 配置 Python 的 logging.FileHandler 的正确方法是什么? - What is the correct way of configuring Python's logging.FileHandler? 在Python中,从变量实例化类的正确方法是什么? - In Python, what's the correct way to instantiate a class from a variable? 使用 Python 在 Spark 中使用 reduceByKey 的正确方法是什么 - What's the correct way of using reduceByKey in Spark using Python Python - 将对象的属性复制到另一个的正确方法是什么? - Python - what is the correct way to copy an object's attributes over to another? 用python扭曲做旋转日志的正确方法是什么? - What's the correct way to do a rotating log with python twisted? 在 Python 多处理中加入线程的正确方法是什么,它们有何不同? - What's the correct way to join threads in Python multiprocessing and how these differ? 在 Python 3 中将字节转换为十六进制字符串的正确方法是什么? - What's the correct way to convert bytes to a hex string in Python 3? 在条件语句中检查对象类型的正确方法是什么-Python - What is the correct way to check an object's type in a conditional statement - python 在 Windows 上设置 Python 语言环境的正确方法是什么? - What is the correct way to set Python's locale on Windows?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM