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. )"
CodePudding user response:
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
CodePudding user response:
if it you need element after last \r\n
then you can do it with split()
and [-1]
without regex
result = {"Comment": test1["SN"].split("\r\n")[-1] }
Full example
test1 = {"SN": "SN: abc123\r\nMAC: 10:ab:cd:30:5C:7C\r\n01-04-2022 Замена"}
lines = test1["SN"].split("\r\n")
result = {"Comment": lines[-1] }
print(result)
Result:
{'Comment': '01-04-2022 Замена'}
EDIT:
If you may have more elements with \r\n
then you may split()
to lines, and later filter lines which not start with SN:
nor MAC:
and later join()
rest of lines into string again.
I added \r\nOtherText
to example data
test1 = {"SN": "SN: abc123\r\nMAC: 10:ab:cd:30:5C:7C\r\n01-04-2022 Замена\r\nOtherText"}
lines = test1["SN"].split("\r\n")
lines = [line for line in lines if not line.startswith(('SN:', 'MAC:'))]
text = "\r\n".join(lines)
result = {"Comment": text }
print(result)