1Ma*_*er1 2 python regex string parsing python-3.x
我已经看到许多解决方案使用,re.split但它并没有解决我的问题。我希望能够拆分我的字符串并将某些字符保留在列表中......很难解释,但这里有一个例子:
文本:
'print("hello world");'
Run Code Online (Sandbox Code Playgroud)
我想要的结果:
["print", "(", "\"", "hello", "world", "\"", ")", ";"]
Run Code Online (Sandbox Code Playgroud)
像 re.split 这样的事情会给我:
["print", "hello", "world"]
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到想要的结果?
你可以试试这个。
import re
text='print("hello world");'
parsed=re.findall(r'(\w+|[^a-zA-Z\s])',text)
print(parsed)
#['print', '(', '"', 'hello', 'world', '"', ')', ';']
Run Code Online (Sandbox Code Playgroud)
\w+ - 捕捉每一个字。
[^a-zA-Z\s]- 捕捉所有不在[a-zA-Z]和不是空间的东西。
编辑:当您想捕获数字和浮点数时,请使用此re表达式\d+\.\d+|\d+|\w+|[^a-zA-Z\s]
\d+- 捕捉数字
\d+\.\d+- 捕捉浮点数。
a='print("hello world",[1,2,3,4,3.15]);'
print(re.findall('\d+\.\d+|\d+|\w+|[^a-zA-Z\s]',a)
#['print', '(', '"', 'hello', 'world', '"', ',', '[', '1', ',', '2', ',', '3', ',', '4', ',', '3.15', ']', ')', ';']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |