gpt4 book ai didi

python - 解析转义字符

转载 作者:行者123 更新时间:2023-11-28 20:10:28 25 4
gpt4 key购买 nike

使用 Python,我正在尝试解析这样的字符串:

"hello" "I am an example" "the man said:\"hello!\""

进入这些 token :

1) hello
2) I am an example
3) the man said: "hello!"

re.findall(r'"[^"]*"', str) 之类的东西很接近,但无法处理转义字符 (\)。我很好奇什么样的 pythonic有一些方法可以在不求助于 for 循环或大型解析器包的情况下处理转义字符。

最佳答案

这很适合正则表达式:

re.findall(r'"(?:\\.|[^"\\])*"', str)

解释:

"        # Match a "
(?: # Match either...
\\. # an escaped character (\\, \" etc.)
| # or
[^"\\] # any character except " or \
)* # any number of times
" # Match a "

这将正确处理转义的反斜杠:

>>> import re
>>> test = r'"hello" "Hello\\" "I am an example" "the man said:\"hello!\\\""'
>>> for match in re.findall(r'"(?:\\.|[^"\\])*"', test):
... print(match)
...
"hello"
"Hello\\"
"I am an example"
"the man said:\"hello!\\\""

关于python - 解析转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349411/

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