Python正则表达式替换字符串中的每第二次出现

发布于 2025-01-10 15:20:50 字数 1037 浏览 0 评论 0原文

我有一个包含如下数据的字符串:

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"

我想用 "," 替换 "],[" 的每第二次迭代,因此它看起来像这样:

str2 = "[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]"

到目前为止,这是我的情况:

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
s2 = re.sub(r"],\[", ',', str1)
print(s2)

我试图解决这个问题:

(.*?],\[){2}

但它似乎没有给我带来想要的结果。

我尝试使用循环,但仅成功替换了第二次出现的情况,并且在使用此处找到的示例代码后没有任何内容。代码是:

import re

def replacenth(string, sub, wanted, n):
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    print(newString)
For these variables:

string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5

谢谢。

I have a string with data that looks like this:

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"

I would want to replace every second iteration of "],[" with "," so it will look like this:

str2 = "[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]"

Here is was I have so far:

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
s2 = re.sub(r"],\[", ',', str1)
print(s2)

I was trying to mess around with this:

(.*?],\[){2}

But it does not seem to yield me the desired results.

I tried using loops but I only managed to replace only the second occurrence and nothing after using this sample code I found here. And the code is:

import re

def replacenth(string, sub, wanted, n):
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    print(newString)
For these variables:

string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5

Thank you.

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

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

发布评论

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

评论(4

岁月染过的梦 2025-01-17 15:20:50

您可以使用

import re
from itertools import count

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
c = count(0)
print( re.sub(r"],\[", lambda x: "," if next(c) % 2 == 0 else x.group(), str1) )
# => [2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]

Python 演示

正则表达式是相同的,],\[,它匹配文字],[文本。

c = count(0) 初始化计数器,其值在用作替换参数的 lambda 表达式内每次匹配时递增。当计数器为偶数时,匹配项将替换为逗号,否则保持原样。

You can use

import re
from itertools import count

str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
c = count(0)
print( re.sub(r"],\[", lambda x: "," if next(c) % 2 == 0 else x.group(), str1) )
# => [2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]

See the Python demo.

The regex is the same, ],\[, it matches a literal ],[ text.

The c = count(0) initializes the counter whose value is incremented upon each match inside a lambda expression used as the replacement argument. When the counter is even, the match is replaced with a comma, else, it is kept as is.

∞觅青森が 2025-01-17 15:20:50

您可以捕获您想要保留的部分。

  1. (\[[^]]+) - 捕获 [ 以及直到但不包括下一个 ]
  2. ],\[ 的 所有内容 - 匹配 ],[
  3. ([^]]+) - 捕获直到但不包括下一个 ] 的所有内容
>>> re.sub(r"(\[[^]]+)],\[([^]]+)", r"\1,\2", str1)
'[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]'

You could capture the parts you want to keep.

  1. (\[[^]]+) - capture [ and everything up to but not including the next ]
  2. ],\[ - match ],[
  3. ([^]]+) - capture everything up to but not including next ]
>>> re.sub(r"(\[[^]]+)],\[([^]]+)", r"\1,\2", str1)
'[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]'
廻憶裏菂餘溫 2025-01-17 15:20:50

这是仅使用正则表达式执行此操作的另一种方法:

import re

text = '[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]'

print(re.sub(r'],\[(.*?])', r',\1', text))

输出:

[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]

Here is another way to do it only using regex:

import re

text = '[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]'

print(re.sub(r'],\[(.*?])', r',\1', text))

Output:

[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]
寻找我们的幸福 2025-01-17 15:20:50

Wiktor 解决方案的更简单版本,使用 itertools.cycle 代替:

c = cycle((",", "],["))
print( re.sub(r"],\[", lambda x: next(c), str1) )
c = cycle((True, False))
print( re.sub(r"],\[", lambda x: "," if next(c) else x.group(), str1) )

Simpler versions of Wiktor's solution, using itertools.cycle instead:

c = cycle((",", "],["))
print( re.sub(r"],\[", lambda x: next(c), str1) )
c = cycle((True, False))
print( re.sub(r"],\[", lambda x: "," if next(c) else x.group(), str1) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文