Python Regex在两个索引值之间找到所有字符

发布于 2025-01-17 08:28:51 字数 476 浏览 2 评论 0 原文

寻找一种使用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命令可以执行此操作?

Looking for a way to use a Python regex to extract all the characters in a string between to indexes. My code is below:

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)

What I am trying to figure out is to somehow use a and b to get z = "loops" in txt2 (the rewrite of txt). Is there a python regex command to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

对你而言 2025-01-24 08:28:51

您可以使用 z = txt [a:b] a b indices之间提取所有字符。

you can use z = txt[a:b] to extract all characters between a and b indices.

飞烟轻若梦 2025-01-24 08:28:51

为什么不使用切片(显而易见的方式)?

z = txt2[a:b]
print(z)  # loops

如果您确实想要使用正则表达式,则需要使用.字符a次才能到达a,因为Regex没有直接索引。然后获取下一个 b - a 字符。在您的情况下,您最终会得到 (?<=.{5}).{5} 模式。 (?<=.{5}) 部分是肯定的后向断言。

pat = rf"(?<=.{{{str(a)}}}).{{{str(b - a)}}}"
print(re.search(pat, txt2))

输出:

<re.Match object; span=(5, 10), match='loops'>

Why not using slices(the obvious way)?

z = txt2[a:b]
print(z)  # loops

If you really want to use regex, you need to consume a . character a times to reach a because Regex doesn't have indexing directly. Then get the next b - a characters. In your case you end up with (?<=.{5}).{5} pattern. (?<=.{5}) part is a positive lookbehind assertion.

pat = rf"(?<=.{{{str(a)}}}).{{{str(b - a)}}}"
print(re.search(pat, txt2))

output:

<re.Match object; span=(5, 10), match='loops'>
归属感 2025-01-24 08:28:51
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."
txt3 = list(txt2)
xy = txt3[a:b]
z = ""
for item in xy:
    
    z = z + item

print(z)
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."
txt3 = list(txt2)
xy = txt3[a:b]
z = ""
for item in xy:
    
    z = z + item

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