等级组的组不均匀
我对Regex中使用的术语不好,因此为这个问题选择合适的标题对我来说有多困难,所以请释放建议一个好的标题。
但是无论如何我都有这个TXT和REGEX表达式的
import re
txt = """
%power {s}
shop %power {w}
%electricity {t}
""".replace('\n',' ')
x = re.findall("((\%?\w+\s)*)\{([^\}]*)\}",txt)
结果是
[('%power','%power','s'),('shop%power','%power','w'),( “%电”,“%电”,“ t”)]
但是我打算获得
[('%power','s'),('shop','%power','w'),(“%equiction”,“ t')]
那么我该如何实现所需的呢?
I'm not good with terms used in regex, so picking a suitable title for this question is some how difficult for me, so feel free the suggest a good title.
but anyway I have this txt and regex expression
import re
txt = """
%power {s}
shop %power {w}
%electricity {t}
""".replace('\n',' ')
x = re.findall("((\%?\w+\s)*)\{([^\}]*)\}",txt)
the result is
[('%power ', '%power ', 's'), ('shop %power ', '%power ', 'w'), ('%electricity ', '%electricity ', 't')]
but I was intended to get
[('%power ', 's'), ('shop ', '%power ', 'w'), ('%electricity ', 't')]
so how can I achieve the desired?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
You need to
pip install regex
and then useSee the
输出:
regex.finditer
usageregex.finditer
方法返回 itoble 而不是列表。 It has an implication that you cannot re-use列表理解中的x
。In order to re-use the contents of
x
, eitherYou need to
pip install regex
and then useSee the Python demo.
Output:
NOTE on
regex.finditer
usageThe
regex.finditer
method returns an iterable, not a list. It has an implication that you cannot re-use thex
inside a list comprehension.In order to re-use the contents of
x
, either convert it to a list (list(x)
), or use the approach above, use it only once to get the necessary output structure, and do whatever you need with the result.