arrays - Manipulating Matched values in Regex C# -
i have read text file , matched data interested in. question is, best way manipulate data have matched? code reading text file is.
openfiledialog dialog = new openfiledialog(); dialog.filter = "all files (*.*)|*.*"; //dialog.initialdirectory = "c:\\"; dialog.title = "select text file"; if (dialog.showdialog() == dialogresult.ok) { string fname = dialog.filename; // selected file label1.text = fname; if (string.isnullorempty(richtextbox1.text)) { var matches1 = regex.matches(system.io.file.readalltext(fname), @"l10 p\d\d\d r \s\s\s\s\s\s\s") .cast<match>() .select(m => m.value) .tolist(); richtextbox1.lines = matches1.toarray(); }
the result looks like:
l10 p015 r +4.9025
and need this:
#2015=4.9025
l10
excluded, p015
turns #2015
, r
, +
turn =
, , number stays same.
use capturing groups:
first change regex to:
l10 p(?<key>\d{3}) r \s(?<val>\s{6})
the
(?<name>
...)
syntax lets declare named capturing group. can later retrieve value matched group.next, when have match object, can extract matching group contents
match.groups["key"].value
,match.groups["val"].value
, that:.select(m => string.format("#2{0}={1}", m.groups["key"].value, m.groups["val"].value))
Comments
Post a Comment