1

How can I make regular expressions work with dictionary?

Example:

my_log:
Received block blk_-967145856473901804 of size 67108864 from /10.250.6.191
Received block blk_8408125361497769001 of size 67108864 from /10.251.70.211

My dictionary:
key_log = {"Received block (.*) of size ([-]?[0-9]+) from (.*)": 1}

My code:
for line in my_log:
        key_id = key_log[my_log]
        print (key_id)

My code is not working?

2
  • It's not clear what you are trying to achieve here. Do you want to print lines which only match your regex ?? Commented Feb 28, 2019 at 16:32
  • Thanks! trying save my_log in to csv file, and if string in my_log match my_dictionary then my code write "1" into my csv file Commented Mar 1, 2019 at 1:58

1 Answer 1

0

I would use an ENUM instead of a dictionary to do it. Below is the code:

import re
import csv
from enum import Enum

#regex model
class Regex(Enum):
    ONE = "Received block (.*) of size ([-]?[0-9]+) from (.*)"
    TWO = "some other regex"

    @classmethod
    def match_value(cls, value):
        for item in cls:
            if re.match(pattern=item.value, string=value):
                return item

def main():
    with open(file='source.log', mode='r', encoding='utf-8') as f:
        for line in f.readlines():
            _match = Regex.match_value(value=line)
            if _match is not None:
                if _match.name == 'ONE':
                    with open(file='target.csv', mode='a') as csv_file:
                        csv_writer = csv.writer(csv_file)
                        csv_writer.writerow([1])
                if _match.name == 'TWO':
                    with open(file='target.csv', mode='a') as csv_file:
                        csv_writer = csv.writer(csv_file)
                        csv_writer.writerow([2])


if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.