提取括号内的字符串-PYTHON [英] Extract string within parentheses - PYTHON

查看:495
本文介绍了提取括号内的字符串-PYTHON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"Name(something)",并且我试图在括号内提取字符串的一部分!

I have a string "Name(something)" and I am trying to extract the portion of the string within the parentheses!

我尝试了以下解决方案,但似乎没有得到我想要的结果.

Iv'e tried the following solutions but don't seem to be getting the results I'm looking for.

n.split('()')

name, something = n.split('()')

推荐答案

您可以使用简单的正则表达式来捕获括号之间的所有内容:

You can use a simple regex to catch everything between the parenthesis:

>>> import re
>>> s = 'Name(something)'
>>> re.search('\(([^)]+)', s).group(1)
'something'

正则表达式匹配第一个(",然后匹配所有不是一个)":

The regex matches the first "(", then it matches everything that's not a ")":

  • \(从字面上匹配字符("
  • 捕获组([^)]+)贪婪地匹配不属于)"的任何内容
  • \( matches the character "(" literally
  • the capturing group ([^)]+) greedily matches anything that's not a ")"

这篇关于提取括号内的字符串-PYTHON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆