在Python中获取括号内的字符串 [英] Get the string within brackets in Python

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

问题描述

我有一个示例字符串 <alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card] ...>, created=1324336085, description='Customer for My Test App', livemode=假>

我只想要值 cus_Y4o9qMEZAugtnW 而不是 card(它在另一个 [] 中)

I only want the value cus_Y4o9qMEZAugtnW and NOT card (which is inside another [])

我怎样才能在 Python 中以最简单的方式做到这一点?也许通过使用 RegEx(我不擅长)?

How could I do it in easiest possible way in Python? Maybe by using RegEx (which I am not good at)?

推荐答案

怎么样:

import re

s = "alpha.Customer[cus_Y4o9qMEZAugtnW] ..."
m = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print m.group(1)

对我来说这个打印:

cus_Y4o9qMEZAugtnW

请注意,对 re.search(...) 的调用会找到正则表达式的第一个匹配项,因此它不会找到 [card] 除非您再次重复搜索.

Note that the call to re.search(...) finds the first match to the regular expression, so it doesn't find the [card] unless you repeat the search a second time.

这里的正则表达式是一个python 原始字符串文字,这基本上意味着反斜杠不被视为特殊字符,而是传递给 re.search() 方法不变.正则表达式的部分是:

The regular expression here is a python raw string literal, which basically means the backslashes are not treated as special characters and are passed through to the re.search() method unchanged. The parts of the regular expression are:

  1. \[ 匹配文字 [ 字符
  2. ( 开始一个新组
  3. [A-Za-z0-9_] 是匹配任何字母(大写或小写)、数字或下划线的字符集
  4. + 匹配前面的元素(字符集)一次或多次.
  5. ) 结束组
  6. \] 匹配文字 ] 字符
  1. \[ matches a literal [ character
  2. ( begins a new group
  3. [A-Za-z0-9_] is a character set matching any letter (capital or lower case), digit or underscore
  4. + matches the preceding element (the character set) one or more times.
  5. ) ends the group
  6. \] matches a literal ] character

正如 D K 所指出的,正则表达式可以简化为:

As D K has pointed out, the regular expression could be simplified to:

m = re.search(r"\[(\w+)\]", s)

因为 \w 是一个特殊的序列,这意味着与 [a-zA-Z0-9_] 相同,这取决于 re.LOCALEre.UNICODE 设置.

since the \w is a special sequence which means the same thing as [a-zA-Z0-9_] depending on the re.LOCALE and re.UNICODE settings.

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

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