等级组的组不均匀

发布于 2025-02-08 11:08:11 字数 458 浏览 3 评论 0原文

我对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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人 2025-02-15 11:08:11

You need to pip install regex and then use

import regex
txt = """
%power {s}
shop %power ow {w}
%electricity {t}
""".replace('\n',' ')
x = regex.finditer(r"(%?\w+\s)*\{([^{}]*)}", txt)
z = [tuple(y.captures(1) + y.captures(2)) for y in x] 
print(z)

See the

输出:

[('%power ', 's'), ('shop ', '%power ', 'ow ', 'w'), ('%electricity ', 't')]

regex.finditer usage

regex.finditer方法返回 itoble 而不是列表。 It has an implication that you cannot re-use列表理解中的x
In order to re-use the contents of x, either

You need to pip install regex and then use

import regex
txt = """
%power {s}
shop %power ow {w}
%electricity {t}
""".replace('\n',' ')
x = regex.finditer(r"(%?\w+\s)*\{([^{}]*)}", txt)
z = [tuple(y.captures(1) + y.captures(2)) for y in x] 
print(z)

See the Python demo.

Output:

[('%power ', 's'), ('shop ', '%power ', 'ow ', 'w'), ('%electricity ', 't')]

NOTE on regex.finditer usage

The regex.finditer method returns an iterable, not a list. It has an implication that you cannot re-use the x 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文