Python正则表达式替换字符串中的每第二次出现
我有一个包含如下数据的字符串:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
Python 演示。
正则表达式是相同的,
],\[
,它匹配文字],[
文本。c = count(0)
初始化计数器,其值在用作替换参数的 lambda 表达式内每次匹配时递增。当计数器为偶数时,匹配项将替换为逗号,否则保持原样。You can use
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.您可以捕获您想要保留的部分。
(\[[^]]+)
- 捕获[
以及直到但不包括下一个]
],\[ 的 所有内容
- 匹配],[
([^]]+)
- 捕获直到但不包括下一个]
的所有内容You could capture the parts you want to keep.
(\[[^]]+)
- capture[
and everything up to but not including the next]
],\[
- match],[
([^]]+)
- capture everything up to but not including next]
这是仅使用正则表达式执行此操作的另一种方法:
输出:
Here is another way to do it only using regex:
Output:
Wiktor 解决方案的更简单版本,使用
itertools.cycle
代替:Simpler versions of Wiktor's solution, using
itertools.cycle
instead: