['<field name="name"/>', '<field name="location_id" options="{\'no_create\': True}" string="来自" groups="stock.group_stock_multi_locations" optional="show"/>', '<field name="location_dest_id" options="{\'no_create\': True}" string="至" groups="stock.group_stock_multi_locations" optional="show"/>', '<field name="partner_id" optional="show"/>', '<field name="user_id" optional="hide"/>', '<field name="scheduled_date" optional="show"/>', '<field name="origin" optional="show"/>', '<field name="backorder_id" optional="hide"/>', '<field name="state" optional="show"/>', '<field name="priority" optional="hide"/>', '<field name="picking_type_id" optional="hide"/>', '<field name="company_id" groups="base.group_multi_company" optional="show"/>', '<field name="activity_exception_decoration" widget="activity_exception"/>']如何获列表中name=""中引号中的内容,引号有可能是单引号或者双引号
时间: 2023-07-24 19:13:49 浏览: 40
要从给定的字符串列表中获取`name=""`中引号中的内容,可以使用正则表达式方法。以下是一个示例代码片段,可以在Python中使用re模块来实现:
```python
import re
def extract_names_from_list(lst):
names = []
pattern = r'name=(\'|")([^\'"]*?)\1'
for string in lst:
matches = re.findall(pattern, string)
for match in matches:
names.append(match[1])
return names
# 示例用法
string_list = ['<field name="name"/>', '<field name="location_id" options="{\'no_create\': True}" string="来自" groups="stock.group_stock_multi_locations" optional="show"/>', '<field name="location_dest_id" options="{\'no_create\': True}" string="至" groups="stock.group_stock_multi_locations" optional="show"/>', '<field name="partner_id" optional="show"/>', '<field name="user_id" optional="hide"/>', '<field name="scheduled_date" optional="show"/>', '<field name="origin" optional="show"/>', '<field name="backorder_id" optional="hide"/>', '<field name="state" optional="show"/>', '<field name="priority" optional="hide"/>', '<field name="picking_type_id" optional="hide"/>', '<field name="company_id" groups="base.group_multi_company" optional="show"/>', '<field name="activity_exception_decoration" widget="activity_exception"/>']
names = extract_names_from_list(string_list)
print(names)
```
在这个示例中,我们定义了一个`extract_names_from_list()`函数,它接受一个字符串列表作为输入。然后,我们使用正则表达式模式`r'name=(\'|")([^\'"]*?)\1'`来匹配引号中的内容。其中`(\'|")`表示匹配单引号或双引号,`([^\'"]*?)`表示匹配除了单引号和双引号之外的任意字符(非贪婪模式),`\1`表示与第一个括号内的内容相匹配(即匹配到的引号类型)。
我们使用`re.findall()`函数来查找所有匹配的结果,并使用循环将匹配到的内容添加到名字列表中。最后,返回名字列表。
请注意,如果字符串中没有匹配到引号内容,将会被忽略。在示例中,只有`<field name="name"/>`匹配到了引号内容,因此只有一个结果被添加到名字列表中。输出结果将会是`['name']`。