I have an array of strings that I want to extract specific content from:
我有一个字符串数组,我想从中提取特定的内容:
['link.description', 'button.text]] </li>']
I want to get the following output:
我想得到如下输出:
link.description
button.text
For each string in the array, I do the following:
对于数组中的每个字符串,我执行以下操作:
str = re.findall('(.*?)\]+', str)
With the above regex, I can only get button.text. How would I get both link.description and button.text? I tried using:
使用上面的regex,我只能获得button.text。如何同时获得link.description和button.text?我试着使用:
str = re.findall('(.*?)\]*', str)
But the above just gives me a bunch of blanks in the return str.
但上面只是给了我返回str中的一些空格。
2 个解决方案
#1
3
You don't need regex for a simple task like this. Besides, your code will probably make more sense without regex.
像这样的简单任务不需要regex。此外,如果没有regex,您的代码可能会更有意义。
In this case, you can simply use str.split()
:
在这种情况下,只需使用string .split():
>>> thingies = ['link.description', 'button.text]] </li>']
>>> different_thingies = [thingy.split(']')[0] for thingy in thingies]
>>> different_thingies
['link.description', 'button.text']
#2
0
Hm, try \]+. Is that what you want? (Asterisk says "match zero times or more" which -as you can see- matches really often.)
嗯,试试\]+。这是你想要的吗?(Asterisk表示“匹配零次或更多”,你可以看到,这种匹配非常频繁。)
#1
3
You don't need regex for a simple task like this. Besides, your code will probably make more sense without regex.
像这样的简单任务不需要regex。此外,如果没有regex,您的代码可能会更有意义。
In this case, you can simply use str.split()
:
在这种情况下,只需使用string .split():
>>> thingies = ['link.description', 'button.text]] </li>']
>>> different_thingies = [thingy.split(']')[0] for thingy in thingies]
>>> different_thingies
['link.description', 'button.text']
#2
0
Hm, try \]+. Is that what you want? (Asterisk says "match zero times or more" which -as you can see- matches really often.)
嗯,试试\]+。这是你想要的吗?(Asterisk表示“匹配零次或更多”,你可以看到,这种匹配非常频繁。)