What should I add or what other way is there?
Question:
I have a dictionary:
test1 = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
I wrote a regular expression in the code:
name_match_3 = re.search(r"(rn.+)", 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:7Crn01-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"(rn.+)"
Answers:
If SN
and MAC
are always directed at the start of a string, then use
rn(.+)$
Python Example
import re
test = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
match = re.search(r"rn(.+)$", test.get("SN"))
result = {"Comment": match.group(1) if match else None} # {'Comment': '01-04-2022 Замена'}
Edit
Otherwise, you can use the following regex
(?:^|rn)((?:(?!SN|MAC|rn).)+)
You can add other keys next to SN
and MAC
as well.
See the regex demo
if it you need element after last rn
then you can do it with split()
and [-1]
without regex
result = {"Comment": test1["SN"].split("rn")[-1] }
Full example
test1 = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
result = {"Comment": test1["SN"].split("rn")[-1] }
print(result)
Result:
{'Comment': '01-04-2022 Замена'}
I have a dictionary:
test1 = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
I wrote a regular expression in the code:
name_match_3 = re.search(r"(rn.+)", 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:7Crn01-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"(rn.+)"
If SN
and MAC
are always directed at the start of a string, then use
rn(.+)$
Python Example
import re
test = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
match = re.search(r"rn(.+)$", test.get("SN"))
result = {"Comment": match.group(1) if match else None} # {'Comment': '01-04-2022 Замена'}
Edit
Otherwise, you can use the following regex
(?:^|rn)((?:(?!SN|MAC|rn).)+)
You can add other keys next to SN
and MAC
as well.
See the regex demo
if it you need element after last rn
then you can do it with split()
and [-1]
without regex
result = {"Comment": test1["SN"].split("rn")[-1] }
Full example
test1 = {"SN": "SN: abc123rnMAC: 10:ab:cd:30:5C:7Crn01-04-2022 Замена"}
result = {"Comment": test1["SN"].split("rn")[-1] }
print(result)
Result:
{'Comment': '01-04-2022 Замена'}