簡體   English   中英

匹配這個的 python 正則表達式是什么?

[英]What will be the python regex to match this?

給定這個字符串:

var python_books = {
   'name': 'Python Notebooks',
   'sub-menu': [{
             'name' : 'Python Research Notebook',
             'snippet' : [
                 'import os, sys, json, time',
                 '',
                 'import numpy as np',
                 'import pandas as pd',
                 'import matplotlib.pyplot as plt',
                 'from scipy import stats',
                 '',
                 '%matplotlib inline',
                 'plt.style.use("ggplot")',
                 '%config InlineBackend.figure_format = "retina"',
              ]
         },
         {'name': 'Getting Data', 'sub-menu': []},
         {'name': 'Visualizations', 'sub-menu': []}
         ]
         };

我想要一個正則表達式,它可以匹配 [...] 這些方括號之間的“片段”中的所有內容。 我已經嘗試過這個正則表達式: regex = r"(?:'Python Research Notebook',\s*'snippet': \[(.|\n)*?\])" 但我想從正則表達式中排除這部分: 'Python Research Notebook', 'snippet':
正后視也不起作用,因為它包含由於\s*引起的可變長度寬度。 我該怎么做呢?

試試這個

var_python_books = {
    'name': 'Python Notebooks',
    'sub-menu': [{
        'name': 'Python Research Notebook',
        'snippet': [
            'import os, sys, json, time',
            '',
            'import numpy as np',
            'import pandas as pd',
            'import matplotlib.pyplot as plt',
            'from scipy import stats',
            '',
            '%matplotlib inline',
            'plt.style.use("ggplot")',
            '%config InlineBackend.figure_format = "retina"',
        ]
    },
        {'name': 'Getting Data', 'sub-menu': []},
        {'name': 'Visualizations', 'sub-menu': []}
    ]
};

for i in var_python_books['sub-menu']:
    if i.get('snippet'):
        print(i['snippet'])

>>> ['import os, sys, json, time', '', 'import numpy as np', 'import pandas as pd', 'import matplotlib.pyplot as plt', 'from scipy import stats', '', '%matplotlib inline', 'plt.style.use("ggplot")', '%config InlineBackend.figure_format = "retina"']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM