c# - Regex : How to extract some fields in text -
i've text file contains below informations :
add comment=user1 disabled=yes name=usera password=123456 profile=\ internet-128k service=pppoe add name=user2 password=123 profile=internet-2m service=pppoe add disabled=yes name=user3 password=316 profile=internet-2m service=\ pppoe add disabled=yes name=user4 password=1216 profile=internet-512k service=\ pppoe add caller-id=8c:89:a5:68:18:9a name=user5 password=308 profile=\ internet-256k remote-ipv6-prefix=::/64 service=pppoe ...
as can see each row starts add
contains information(fields) example comment, disabled, name, password, profile
, on. want extract pieces of information(fields) in each row. how can that?
first can extract each block, second extract information:
string text = file.readalltext("sample.txt"); string[] items = regex.matches(text, "add .*?(?=\r\nadd|$)", regexoptions.singleline) .cast<match>() .select(m => m.value) .toarray(); foreach (string item in items) { string line = regex.replace(item, @"\\\s*\r\n\s*", string.empty); keyvaluepair<string, string>[] pairs = regex.matches(line, @"(?<name>\w+)=(?<value>.*?)(?=\w+=|$)") .cast<match>() .select(m => new keyvaluepair<string, string>(m.groups["name"].value, m.groups["value"].value)) .toarray(); console.writeline(line); foreach (var pair in pairs) console.writeline("{0} = {1}", pair.key, pair.value); }
Comments
Post a Comment