Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用正则表达式查找Python 3中第一个括号内的内容_Python_Regex - Fatal编程技术网

使用正则表达式查找Python 3中第一个括号内的内容

使用正则表达式查找Python 3中第一个括号内的内容,python,regex,Python,Regex,以下是我的示例字符串: [true, {"name": "NameofItem", "amount": "1", "price": 100, "sellerName": "Sellername1", "sellerId": 1}, {"name": "NameofItem2", "amou

以下是我的示例字符串:

[true, {"name": "NameofItem", "amount": "1", "price": 100, "sellerName": "Sellername1", "sellerId": 1},
{"name": "NameofItem2", "amount": "1", "price": 101, "sellerName": "Sellername2", "sellerId": 2}, 22250]
我需要找到一种方法来获取“price”的第一个实例及其关联整数。 我想我可以用re.match和

(\{.*?\})
获取第一组内容,然后转换为字典,但我似乎无法实现这一点


非常感谢您的帮助。

不要使用正则表达式来解析格式良好的JSON。使用内置函数将JSON字符串解析为内存中的列表数据结构。然后,您可以使用
L[1]
访问列表中的第一个元素,并使用
L[1][“price”]
访问该词典中的
“price”
键:

>>s='[true,{“name”:“NameofItem”,“amount”:“1”,“price”:100,“sellerName”:“Sellername1”,“sellerId”:1},{“name”:“NameofItem2”,“amount”:“1”,“price”:101,“sellerName”:“Sellername2”,“sellerId”:2},22250]'
>>>导入json
>>>L=json.loads
>>>L
[True,{'name':'NameofItem','amount':'1','price':100,'sellerName':'Sellername1','sellerId':1},{'name':'NameofItem2','amount':'1','price':101,'sellerName':'Sellername2','sellerId':2},22250]
>>>L[1][“价格”]
100
>>>类型(L[1][“价格”])

如果您只需要“价格”:100,那么您可以使用
\“价格”:\d+
-您能试试这个吗?我认为re.match只发现了第一次出现的模式欢迎来到SO!有没有理由不使用
JSON.loads
将此JSON加载到内存中的数据结构中?然后,您可以访问属性并在不使用正则表达式的情况下明智地遍历它,例如
L[1][“price”]
。这是否回答了您的问题?当使用re.match时,它会找到“none”,但当使用re.findall时,正则表达式工作得很好,可以找到价格的所有实例。不确定为什么re.match找不到第一个实例。@ggorlen我对python还是很陌生!我不知道json.loads是个东西。感谢you@ggorlen-当你发布你的答案时,我的页面没有被引用。
>>> s = '[true,{"name":"NameofItem","amount":"1","price":100,"sellerName":"Sellername1", "sellerId":1},{"name":"NameofItem2","amount":"1","price":101,"sellerName":"Sellername2","sellerId":2},22250]'
>>> import json
>>> L = json.loads(s)
>>> L
[True, {'name': 'NameofItem', 'amount': '1', 'price': 100, 'sellerName': 'Sellername1', 'sellerId': 1}, {'name': 'NameofItem2', 'amount': '1', 'price': 101, 'sellerName': 'Sellername2', 'sellerId': 2}, 22250]
>>> L[1]["price"]
100
>>> type(L[1]["price"])
<class 'int'>
import json
print(json.loads(input_string)[1]['price'])