正则表达式匹配重复的字符串python

时间:2022-09-13 00:19:54

I got strings which go:

我得到的字符串:

abc123abc123abc123

abc123abc123abc123

abc123

ABC123

abc123abc123abc123abc123abc123abc123

abc123abc123abc123abc123abc123abc123

etc (varying units of abc123 which I don't know the length of repeat)

等(abc123的不同单位,我不知道重复的长度)

The task is to extract the first 1 and first a and the last c and last 3. Is it possible to do it with 1 regex and how exactly if it is possible? I kept count of the repeating units and based on the count I have been able to perform the task with a few regex, but would like to use one regex if possible. Thanks

任务是提取第一个1和第一个a和最后一个c和最后一个3.是否可以使用1个正则表达式以及它是如何实现的?我一直在计算重复单位,根据计数,我已经能够用一些正则表达式执行任务,但是如果可能的话,我想使用一个正则表达式。谢谢

Edit: In the real situation. It is more like a:(a number)bc:(a number)1:(a number)23:(a number) etc and I have to capture the first a number, the first 1 number, the last c number and the last 3 number.

编辑:在实际情况。它更像是:(一个数字)bc :(一个数字)1 :(一个数字)23 :(一个数字)等我必须捕获第一个数字,前1个数字,最后一个c数字和最后3个号码。

Jeff

杰夫

1 个解决方案

#1


3  

This is easiest done using two regexen. "^(a)bc(1)23" and "ab(c)12(3)$". It may be possible to merge these two, but the regular expression will get pretty unreadable.

这是使用两个regexen最简单的方法。 “^(a)bc(1)23”和“ab(c)12(3)$”。有可能合并这两个,但正则表达式将变得非常难以理解。

#1


3  

This is easiest done using two regexen. "^(a)bc(1)23" and "ab(c)12(3)$". It may be possible to merge these two, but the regular expression will get pretty unreadable.

这是使用两个regexen最简单的方法。 “^(a)bc(1)23”和“ab(c)12(3)$”。有可能合并这两个,但正则表达式将变得非常难以理解。