Search code examples
pythonregexpython-re

What should I add or what other way is there?


I have a dictionary:

test1 = {"SN": "SN: abc123\r\nMAC: 10:ab:cd:30:5C:7C\r\n01-04-2022 Замена"}

I wrote a regular expression in the code:

name_match_3 = re.search(r"(\r\n.+)", test1.get("SN"), flags=re.DOTALL)
dict_miner_regular["Comment"] = (name_match_3.group(1) if name_match_3 else None)

As a result, I'm getting:

result_2 = {"Comment": "MAC: 10:ab:cd:30:5C:7C\r\n01-04-2022 Замена"}

But I also need to remove MAC: 10:ab:cd:30:5C:7C. But it's not everywhere.

As a result, it is necessary to remove SN: and MAC:

result_3 = {"Comment": "01-04-2022 Замена"}

I understand that something needs to be added here --> r"(\r\n.+)"


Solution

  • If SN and MAC are always directed at the start of a string, then use

    \r\n(.+)$
    

    Python Example

    import re
    
    test = {"SN": "SN: abc123\r\nMAC: 10:ab:cd:30:5C:7C\r\n01-04-2022 Замена"}
    match = re.search(r"\r\n(.+)$", test.get("SN"))
    result = {"Comment": match.group(1) if match else None}  # {'Comment': '01-04-2022 Замена'}
    

    Edit

    Otherwise, you can use the following regex

    (?:^|\r\n)((?:(?!SN|MAC|\r\n).)+)
    

    You can add other keys next to SN and MAC as well.

    See the regex demo