regex - Regular expression to match variable=value but ignore trailing blanks and comments -
i trying parse driver inf file , extract "variables" , "values" sections. have come basic regular expression:
"(.+?)\s*=\s*(.+)"
this matches variable fine matches after equals , whitespace. in these files there may optionally trailing comments begin semicolon , dont want match. thought i'd try:
"(.+?)\s*=\s*(.+);?"
but doesnt work. other issue there may white space before semicolon want ignore there may white space within value want match. here examples (using variable first match , value second):
class=display (the variable should "class" , value "display"
defaultdestdir = 11 ; system32 (variable="defaultdestdir" , value="11")
cpuxyz = 16483,au zy xy open ; comment (variable = "cpuxyz" , value = "16483,au zy xy open")
i'm looking expand initial regular expression "value" can cope of above examples.
negative character classes friend
lucky you, have in pocket today.
^([^=\s]+)[ ]*=[ ]*([^;\r\n]+)
in the demo, @ capture groups in right pane.
explanation
- the
^
anchor asserts @ beginning of string - in first
(capture group)
, negative character class[^=\s]+
matches 1 or more chars not=
or whitespace character (which included newlines) [ ]*
matches optional spaces. brackets not needed, there clarity=
matches literal=
[ ]*
matches optional spaces.- in second
(capture group)
, negative character class[^;\r\n]+
matches 1 or more chars not;
or newline characters
Comments
Post a Comment