regex 用于检测Python字典语法的正则表达式

tquggr8v  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(103)

我一直在挣扎,我的头都快炸了,所以我需要用Python编写一个基本的Regex脚本,它可以识别一个字符串是否具有Python字典的格式(模式),使用下面的代码,我只成功地匹配了如下字符串:my_dict = {1: 'apple', 2: 'ball'}
我想匹配像下面这样的东西,它不只是使用数字作为键和字母作为值:

{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
  • ------------字典检测器-------------------
# importing regex module
import re

# printing script purpose
# `\n` is for printing newline
print('\nScript designed to detect whether if user input is a Python dictionary construction.\n')

# getting user input
user_inp = input('Type Text> ')

if user_inp != '{}':
    user_inp = user_inp.replace('}', ',}', 1)

if re.search('''^{((('(\w|\d)*')|(\w|\d)*) *: * (('(\w|\d)*')|(\w|\d)*) *, *)*}$''', user_inp):
    print('yes, a dictionary has been detected.')

else:
    print('No dictionary has been detected.')
von4xj4u

von4xj4u1#

正如评论中提到的,json可能更适合,但如果您仍然想使用regex,这里有一个:

dict_reg = re.compile(r"""
\s*                 # user might leave spaces in front
{                   # the opening curly of dict
(                   # the key-value pair groups begin
\s*                 # user might leave a space
[\"'().,\w]+        # the "key" part: matches strings, tuples, numbers and variables
\s*:\s*             # the colon and possible spaces around
[\"'()\[\].,\w]+    # the "value" part: matches strings, tuples, lists, numbers and variables
\s*                 # again, user might leave a space after writing value
,?                  # the comma that seperates key-value pairs (optional, last one may not have it)
\s*                 # again, user might leave a space
)*                  # the key-value pair groups as many as possible (* implies empty dict is also ok)
}                   # the closing curly of dict
\s*                 # again, user might leave a space because why not
""", re.VERBOSE)

您可以用作:

re.fullmatch(dict_reg, user_inp)

明显不匹配的情况:
算术表达式,例如作为关键字或值的2+5
dict s作为值
嵌套指令
可能还有更多。但是对于基本的字典来说应该还可以。

pdtvr36n

pdtvr36n2#

这不是一个真正的正则表达式解决方案,但如果你使用python,你可以:

def is_dictionary(string) -> bool:
        if type(eval(string)) is dict:
            return True
        else:
            return False

相关问题