简体   繁体   中英

What will be the python regex to match this?

Given this string:

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': []}
         ]
         };

I want a regex which can match everything in 'snippet' between [...] these square brackets. I already have tried this regex: regex = r"(?:'Python Research Notebook',\s*'snippet': \[(.|\n)*?\])" . But I want to exclude this part from regex: 'Python Research Notebook', 'snippet':
Positive lookbehind is also not working since it contains variable length width due to \s* . How do I do this?

try 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': []}
    ]
};

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"']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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