从匹配的字符串中提取子字符串

时间:2019-03-31 00:31:53

标签: regex python-2.7

我尝试在字符串开头匹配Physics2D.IgnoreLayerCollision (8, 9);后从字符串中提取子字符串。子字符串是MAC ID,从位置6开始直到字符串结尾。我知道子字符串方法可以完成这项工作。我很好奇知道正则表达式的实现。

字符串= 24

经过反复试验,我认为这是我所遇到的正则表达式。

2410100:80:a3:bf:72:d45

如何修改此正则表达式以匹配[^24*$](?<=^\S{6}).*$ ,然后从位置24提取子字符串直到行尾?

6

预期结果:https://regex101.com/r/vcvfMx/2

1 个答案:

答案 0 :(得分:2)

您可以使用:

(?<=^24\S{3}).*$

这是一个演示:https://regex101.com/r/HqT0RV/1/

这将为您带来预期的结果(即00:80:a3:bf:72:d45)。但是,这似乎不是有效的MAC地址(末尾的5似乎不是MAC的一部分)。在这种情况下,您应该使用以下内容:

(?<=^24\S{3})(?:[0-9a-f]{2}:){5}[0-9a-f]{2}

演示:https://regex101.com/r/HqT0RV/2

故障:

(?<=            # Start of a positive Lookbehind.
    ^           # Asserts position at the beginning of the string.
    24          # Matches `24` literally.
    \S{3}       # Matches any three non-whitespace characters.
)               # End of the Lookbehind (five characters so far).
(?:             # Start of a non-capturing group.
    [0-9a-f]    # A number between `0` and `9` or a letter between `a` and `f` (at pos. #6).
    {2}         # Matches the previous character class exactly two times.
    :           # Matches `:` literally.
)               # End of the non-capturing group.
{5}             # Matches the previous group exactly five times.
[0-9a-f]        # Any number between `0` and `9` or any letter between `a` and `f`.
{2}             # Matches the previous character class exactly two times.