在Python中获取括号内的字符串
我有一个示例字符串
我只想要值 cus_Y4o9qMEZAugtnW
而不是card
(位于另一个[]
内部)
我怎样才能在Python中以最简单的方式做到这一点? 也许通过使用正则表达式(我不擅长)?
I have a sample string <alpha.Customer[cus_Y4o9qMEZAugtnW] active_card=<alpha.AlphaObject[card] ...>, created=1324336085, description='Customer for My Test App', livemode=False>
I only want the value cus_Y4o9qMEZAugtnW
and NOT card
(which is inside another []
)
How could I do it in easiest possible way in Python?
Maybe by using RegEx (which I am not good at)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
怎么样:
对我来说,打印:
请注意,对
re.search(...)
的调用找到了正则表达式的第一个匹配项,因此它找不到[card]除非您第二次重复搜索。
编辑:这里的正则表达式是一个python 原始字符串文字,这基本上意味着反斜杠不被视为特殊字符并被传递到
re.search( )
方法不变。正则表达式的 部分 为:\[
匹配文字[
字符(
开始一个新组[A-Za-z0-9_]
是匹配任何字母(大写或小写字母)的字符集大小写)、数字或下划线+
匹配前面的元素(字符集))
结束组\]
与文字]
字符编辑: 正如 DK 所指出的,正则表达式可以简化为:
因为
\w
是一个特殊的序列,其含义与[a-zA-Z0-9_ ]
取决于re.LOCALE
和re.UNICODE
设置。How about:
For me this prints:
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.Edit: 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:\[
matches a literal[
character(
begins a new group[A-Za-z0-9_]
is a character set matching any letter (capital or lower case), digit or underscore+
matches the preceding element (the character set) one or more times.)
ends the group\]
matches a literal]
characterEdit: As D K has pointed out, the regular expression could be simplified to:
since the
\w
is a special sequence which means the same thing as[a-zA-Z0-9_]
depending on there.LOCALE
andre.UNICODE
settings.您可以使用
str.split
来做这。然后我们有:
You could use
str.split
to do this.Then we have:
这应该可以完成这项工作:
This should do the job:
礼貌: 返回括号之间文本的正则表达式
courtesy: Regular expression to return text between parenthesis
也可以使用
如果您想查找很多出现的情况,
。另请参阅了解更多信息:
如何找到 a 的所有匹配项Python 中的正则表达式?
You can also use
if there are many occurrences that you would like to find.
See also for more info:
How can I find all matches to a regular expression in Python?
您可以使用
You can use
这个怎么样?使用文件说明的示例:
希望这有帮助:
解释:
\[
:[
是一个元字符,如果您想按字面匹配它,则需要对其进行转义。(.*?)
:以非贪婪的方式匹配所有内容并捕获它。\]
:]
是一个元字符,如果您想按字面匹配它,则需要对其进行转义。How about this ? Example illusrated using a file:
Hope this helps:
Explanation:
\[
:[
is a meta char and needs to be escaped if you want to match it literally.(.*?)
: match everything in a non-greedy way and capture it.\]
:]
is a meta char and needs to be escaped if you want to match it literally.此代码片段也应该有效,但它将返回“[]”内包含的任何文本
This snippet should work too, but it will return any text enclosed within "[]"