Parsing a text file with regex

Viewed 69

For example, I have a sample text file as displayed below that I need to fetch information from:

Sider_DLL: version 6.3.9 (0)
Filename_match: PES2020.exe
handle1 = 40923
debug = 0
game_priority_class = 0x0
livecpk_enabled = 1
lookup_cache_enabled = 1
lua_enabled = 1
lua_gc_opt = step
jit_enabled = 1
luajit_ext_enabled = 1
dummify_uniparam = 1
key-cache_ttl_sec = 10
rewrite-cache.ttl-sec = 10
cache.size = 32

I am wondering if I can use regex in order to get the data in lines 1,2,9, and 13 and output a concatenated string: "version 6.3.9(0)PES2020.exestep10". I have the following line and does not return the right output.

re.findall(r'Sider_DLL:: (\\w\w\w\w\w\w\w\s\d+)[ a-zA-Z]+Filename_match:(a-z)+[ a-zA-Z]+lua_gc_opt= (a-zA-Z)) 
2 Answers

You may try the following find and replace, in regex mode:

Find:    ^.*?Sider_DLL:\s*(.*?)\r?\n.*?Filename_match:\s*(.*?)\r?\n.*?lua_gc_opt\s*=\s*(.*?)\r?\n.*?key-cache_ttl_sec\s*=\s*(.*?)\r?\n.*$
Replace: $1$2$3$4

Demo

You might also find the data using 4 capture groups, and output the 4 concatenated groups like $1$2$3$4

^Sider_DLL: *(\w.*)\r?\nFilename_match: *(\w.*)(?:\r?\n(?!lua_gc_opt *=).*)*\r?\nlua_gc_opt *= *(\w.*)(?:\r?\n(?!key-cache_ttl_sec *=).*)*\r?\nkey-cache_ttl_sec *= *(\d+)
  • ^ Start of string
  • Sider_DLL: *(\w.*)\r?\n Match start of line 1, and capture in group 1 a word char followed by the rest of the line and newline
  • Filename_match: *(\w.*) Match start of line 2 and capture in group 2 a word char followed by the rest of the line
  • (?:\r?\n(?!lua_gc_opt *=).*)*\r?\n Match all the lines that do not start with lua_gc_opt =
  • lua_gc_opt *= *(\w.*) Match lua_gc_opt = and capture in group 3 a word char and the rest of the line
  • (?:\r?\n(?!key-cache_ttl_sec *=).*)*\r?\n Match all lines that do not start with key-cache_ttl_sec =
  • key-cache_ttl_sec *= *(\d+) Match key-cache_ttl_sec = and capture in group 4 one or more digits

Regex demo

Example

import re

regex = r"^Sider_DLL: *(\w.*)\r?\nFilename_match: *(\w.*)(?:\r?\n(?!lua_gc_opt *=).*)*\r?\nlua_gc_opt *= *(\w.*)(?:\r?\n(?!key-cache_ttl_sec *=).*)*\r?\nkey-cache_ttl_sec *= *(\d+)"

test_str = ("Sider_DLL: version 6.3.9 (0)\n"
            "Filename_match: PES2020.exe\n"
            "handle1 = 40923\n"
            "debug = 0\n"
            "game_priority_class = 0x0\n"
            "livecpk_enabled = 1\n"
            "lookup_cache_enabled = 1\n"
            "lua_enabled = 1\n"
            "lua_gc_opt = step\n"
            "jit_enabled = 1\n"
            "luajit_ext_enabled = 1\n"
            "dummify_uniparam = 1\n"
            "key-cache_ttl_sec = 10\n"
            "rewrite-cache.ttl-sec = 10\n"
            "cache.size = 32")

result = ["".join(m) for m in re.findall(regex, test_str)]
print(result)

Output

['version 6.3.9 (0)PES2020.exestep10']
Related