简体   繁体   English

从字符串列表中,仅提取括号内的字符

[英]From list of strings, extract only characters within brackets

I have a list of strings that have variable construction but have a character sequence enclosed in square brackets. 我有一个字符串列表,这些字符串具有可变的结构,但字符序列括在方括号中。 I want to extract only the sequence enclosed by the square brackets. 我只想提取方括号内的序列。 There is only one instance of square brackets per string, which simplifies the process. 每个字符串只有一个方括号实例,这简化了过程。

I am struggling to do so in an elegant manner, and this is clearly a simple problem with Python's large string library. 我正在努力以优雅的方式进行操作,这显然是Python大型字符串库的一个简单问题。

What is a simple expression to do this? 做这个的简单表达是什么?

Check regular expression, "re" 检查正则表达式“ re”

Something like this should do the trick 这样的事情应该可以解决问题

import re

s = "hello_from_adele[this_is_the_string_i_am_looking_for]this_is_not_it"
match = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print match.group(1)

If you provide an example, we can be more specific 如果您提供示例,我们可以更具体

You don't even need re to do this: 您甚至不需要re执行此操作:

In [11]: strng = "This is some text [that has brackets] followed by more text"

In [12]: strng[strng.index("[")+1:strng.index("]")]
Out[12]: 'that has brackets'

This uses string slicing to return the characters inside the brackets. 这使用字符串切片来返回括号内的字符。 index() returns the 0-based position of its argument. index()返回其参数从0开始的位置。 Since we don't want to include the [ at the beginning, we add 1. The second argument of the slice is the stop position, but it is not included in the returned substring, so we don't need to add anything to it. 由于我们不想在开始时包含[ ,所以我们添加1。slice的第二个参数是停止位置,但是它不包含在返回的子字符串中,因此我们不需要为其添加任何内容。

If you prefer not to use regex for whatever reason, it should be easy to do with string splitting since you're guaranteed to have one and only one instance of [ and ] . 如果出于某种原因而不愿意使用regex,则可以很容易地进行字符串分割,因为可以保证只有[]一个实例。

s = "some[string]to check"

_, midright = s.split("[")
target, _ = midright.split("]")

or 要么

target = s.split("[")[1].split("]")[0]  # ewww

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

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