[英]Regex match adjacent digits after second occurrence of character
Stuck with the following issue:遇到以下问题:
I have a string 'ABC.123.456XX' and I want to use regex to extract the 3 numeric characters that come after the second period.我有一个字符串“ABC.123.456XX”,我想使用正则表达式来提取第二个句点之后的 3 个数字字符。 Really struggling with this and would appreciate any new insights, this is the closest I got but its not really close to what I want:
真的为此苦苦挣扎,并希望有任何新的见解,这是我得到的最接近的结果,但它并不真正接近我想要的:
'.*\.(.*?\.\d{3})'
I appreciate any help in advance - thanks.我提前感谢任何帮助 - 谢谢。
If your input will always be in a similar format, like xxx.xxx.xxxxx
, then one solution is string manipulation:如果您的输入始终采用类似的格式,例如
xxx.xxx.xxxxx
,那么一种解决方案是字符串操作:
>>> s = 'ABC.123.456XX'
>>> '.'.join(s.split('.')[2:])[0:3]
Explanation解释
In the line '.'.join(s.split('.')[2:])[0:3]
:在
'.'.join(s.split('.')[2:])[0:3]
行中:
s.split('.')
splits the string into the list ['ABC', '123', '456XX']
s.split('.')
将字符串拆分成列表['ABC', '123', '456XX']
'.'.join(s.split('.')[2:])
joins the remainder of the list after the second element, so '456XX'
'.'.join(s.split('.')[2:])
在第二个元素之后加入列表的其余部分,所以'456XX'
[0:3]
selects the substring from index 0 to index 2 (inclusive), so the result is 456
[0:3]
选择索引0到索引2(含)的substring,所以结果为456
Dot, not-Dot twice then the 3 digits follow in capture group 1点,非点两次,然后在捕获组 1 中跟随 3 位数字
[^.]*(?:\.[^.]*){2}(\d{3})
https://regex101.com/r/qWpfHx/1 https://regex101.com/r/qWpfHx/1
Expanded展开
[^.]*
(?: \. [^.]* ){2}
( \d{3} ) # (1)
This expression might also work just OK:这个表达式也可以正常工作:
[^\r\n.]+\.[^\r\n.]+\.([0-9]{3})
import re
regex = r'[^\r\n.]+\.[^\r\n.]+\.([0-9]{3})'
string = '''
ABC.123.456XX
ABCOUOU.123123123.000871XX
ABCanything_else.123123123.111871XX
'''
print(re.findall(regex, string))
['456', '000', '111']
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com .如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板上进行了解释。 If you'd like, you can also watch in this link , how it would match against some sample inputs.
如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.