我正在学习regex,并且很难从下面的系统需求字符串中找到模式:
"OS: Windows® 7 Processor: Intel Core i3-9100 / AMD Ryzen 3 2300X Memory: 8 GB RAM Graphics: NVIDIA® GeForce® GTX 1050 Ti / AMD Radeon™ RX 560 (4GB VRAM) Storage: 60 GB available space"我做了很多次,但都找不到匹配的。我想根据冒号(:)将结果分组到python字典中,如下所示:
{
'OS': 'Windows® 7',
'Processor': 'Intel Core i3-9100 / AMD Ryzen 3 2300X',
'Memory': '8 GB RAM Graphics: NVIDIA® GeForce® GTX 1050 Ti / AMD Radeon™ RX 560 (4GB VRAM)',
'Storage': '60 GB available space'
}任何帮助都将不胜感激。这是我的工作:regex101。谢谢。
发布于 2022-07-20 02:59:34
您可以在re.findall中使用"(\w+):\s+(.*?)(?=$|\s*\w+:\s+)":一个单词,后面跟着一个冒号和空格,然后尽可能少地使用任何东西,直到字符串结束或另一个单词后面跟着一个冒号和空格为止。
最起码的例子:
s = "OS: Windows® 7 Processor: Intel Core i3-9100 / AMD Ryzen 3 2300X Memory: 8 GB RAM Graphics: NVIDIA® GeForce® GTX 1050 Ti / AMD Radeon™ RX 560 (4GB VRAM) Storage: 60 GB available space"
import re
d = dict(re.findall(r"(\w+):\s+(.*?)(?=$|\s*\w+:\s+)", s))产出:
{'OS': 'Windows® 7',
'Processor': 'Intel Core i3-9100 / AMD Ryzen 3 2300X',
'Memory': '8 GB RAM',
'Graphics': 'NVIDIA® GeForce® GTX 1050 Ti / AMD Radeon™ RX 560 (4GB VRAM)',
'Storage': '60 GB available space'}https://stackoverflow.com/questions/73045458
复制相似问题