Python Regex在两个索引值之间找到所有字符
寻找一种使用Python Regex提取索引之间的字符串中的所有字符的方法。我的代码如下:
import re
txt = "Hula hoops are fun."
x = re.search(r"hoops", txt)
c = x.span()
a = c[0]
b = c[1]
print(a) # prints 5
print(b) # prints 10
txt2 = "Hula loops are fun."
z = re.???(a, b, txt2) #<------ Incorrect
print(z)
我要弄清楚的是以某种方式使用 a
和 b
in z =“ loops”
> txt2 ( txt
的重写)。是否有Python Regex命令可以执行此操作?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
z = txt [a:b]
在a
和b
indices之间提取所有字符。you can use
z = txt[a:b]
to extract all characters betweena
andb
indices.为什么不使用切片(显而易见的方式)?
如果您确实想要使用正则表达式,则需要使用
.
字符a
次才能到达a
,因为Regex没有直接索引。然后获取下一个b - a
字符。在您的情况下,您最终会得到(?<=.{5}).{5}
模式。(?<=.{5})
部分是肯定的后向断言。输出:
Why not using slices(the obvious way)?
If you really want to use regex, you need to consume a
.
charactera
times to reacha
because Regex doesn't have indexing directly. Then get the nextb - a
characters. In your case you end up with(?<=.{5}).{5}
pattern.(?<=.{5})
part is a positive lookbehind assertion.output: