gpt4 book ai didi

Python 正则表达式匹配引号、大括号或括号中的任何内容

转载 作者:行者123 更新时间:2023-12-01 06:34:48 25 4
gpt4 key购买 nike

更新

This is still not entirely the solution so far. It is only for preceding repeated closing characters (e.g )), ]], }}). I'm still looking for a way to capture enclosed contents and will update this.

代码:

>>> import re
>>> re.search(r'(\(.+?[?<!)]\))', '((x(y)z))', re.DOTALL).groups()
('((x(y)z))',)

详细信息:

r'(\(.+?[?<!)]\))'
  • () - 捕获组特殊字符。
  • \(\) - 开始和结束字符(例如 '"(){}[] )
  • .+? - 匹配任何字符内容(与re.DOTALL标志一起使用)
  • [?<!)] - 角色的负面回顾 ) (将其替换为匹配的结束字符)。这基本上会找到任何)字符在 \)字符不位于前面(更多信息 here )。
<小时/>

我试图解析我正在使用的词法分析器的变量赋值语句之类的东西,只是想了解解释器/编译器背后的基本逻辑。

这是我正在处理的基本赋值语句和文字:

az = none
az_ = true
az09 = false
az09_ = +0.9
az_09 = 'az09_'
_az09 = "az09_"
_az = [
"az",
0.9
]
_09 = {
0: az
1: 0.9
}
_ = (
true
)

不知何故,我设法解析了那些简单的赋值,例如 none , true , false和数字文字。这是我目前陷入的困境:

import sys
import re

# validate command-line arguments
if (len(sys.argv) != 2): raise ValueError('usage: parse <script>')

# parse the variable name and its value
def handle_assignment(index, source):
# TODO: handle quotations, brackets, braces, and parenthesis values
variable = re.search(r'[\S\D]([\w]+)\s+?=\s+?(none|true|false|[-+]?\d+\.?\d+|[\'\"].*[\'\"])', source[index:])
if variable is not None:
print('{}={}'.format(variable.group(1), variable.group(2)))
index += source[index:].index(variable.group(2))
return index

# parse through the source element by element
with open(sys.argv[1]) as file:
source = file.read()
index = 0
while index < len(source):
# checks if the line matches a variable assignment statement
if re.match(r'[\S\D][\w]+\s+?=', source[index:]):
index = handle_assignment(index, source)
index += 1

我正在寻找一种方法来捕获这些带有引号、方括号、大括号和圆括号的值。

如果我找到答案,可能会更新这篇文章。

最佳答案

对每个匹配对使用具有多个替代项的正则表达式。

re.match(r'\'.*?\'|".*?"|\(.*?\)|\[.*?\]|\{.*?\}', s)

但是请注意,如果存在嵌套括号,则这将与第一个结束括号匹配,例如如果输入是

(words (and some more words))

结果将是

(words (and some more words)

正则表达式不适合匹配嵌套结构,您应该使用更强大的解析技术。

关于Python 正则表达式匹配引号、大括号或括号中的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59727353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com