RSSregex
RSSregex

Reputation: 169

Extract a sub-string from a matched string

I am attempting to extract a sub-string from a string after matching for 24 at the beginning of the string. The substring is a MAC id starting at position 6 till the end of the string. I am aware that a sub string method can do the job. I am curious to know a regex implementation.

String = 2410100:80:a3:bf:72:d45

After much trial and error, this the reg-ex I have which I think is convoluted.

[^24*$](?<=^\S{6}).*$

How can this reg-ex be modified to match for 24, then extract the substring from position 6 till the end of the line?

https://regex101.com/r/vcvfMx/2

Expected Results: 00:80:a3:bf:72:d45

Upvotes: 1

Views: 65

Answers (1)

41686d6564
41686d6564

Reputation: 19661

You can use:

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

Here's a demo: https://regex101.com/r/HqT0RV/1/

This will get you the result you expect (i.e., 00:80:a3:bf:72:d45). However, that doesn't seem to be a valid MAC address (the 5 at the end seems to be not part of the MAC). In which case, you should be using something like this:

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

Demo: https://regex101.com/r/HqT0RV/2

Breakdown:

(?<=            # 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.

Upvotes: 2

Related Questions