O R*_*ené 1 python regex string split python-re
我正在尝试拆分包含 python 函数的字符串,以便生成的输出将单独的函数保留为列表元素。
s='hello()there()'应该拆分为['hello()', 'there()']
为此,我使用正则表达式先行在右括号上拆分,但不在字符串末尾拆分。
虽然前瞻似乎有效,但我无法)按照各种帖子中的建议将结果保留在结果字符串中。简单地用正则表达式分割会丢弃分隔符:
import re
s='hello()there()'
t=re.split("\)(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
这导致:'hello(', 'there()']。
s='hello()there()'
t=re.split("(\))(?!$)", s)
Run Code Online (Sandbox Code Playgroud)
将分隔符包装为一个组会导致)保留为一个单独的元素:与使用该函数的方法['hello(', ')', 'there()']
一样:filter()
s='hello()there()'
u = list(filter(None, re.split("(\))(?!$)", s)))
Run Code Online (Sandbox Code Playgroud)
再次导致括号作为单独的元素:['hello(', ')', 'there()']
如何拆分这样的字符串以使函数在输出中保持完整?
\w+\(\)匹配一个或多个单词字符,后跟一个左括号和一个右括号> 该部分与 andhello()匹配there()t = re.findall(r"\w+\(\)", s)
Run Code Online (Sandbox Code Playgroud)
['hello()', 'there()']
Run Code Online (Sandbox Code Playgroud)
Edition:
.*?是非贪婪匹配,这意味着它将匹配括号中尽可能少的字符。
s = "hello(x, ...)there(6L)now()"
t = re.findall(r"\w+\(.*?\)", s)
print(t)
Run Code Online (Sandbox Code Playgroud)
['hello(x, ...)', 'there(6L)', 'now()']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |