Ignore comments with a space in the regular expression

How can I change the following line of code (which reads the parameter names in config_file):

re.findall('Parameter.*', config_file)

to ignore lines containing comment character ( %) left? that is, in the following example,

Parameter: A
%Parameter: B
  %  Parameter: C
 Parameter: D %the best parameter

only A and D match?

+4
source share
2 answers

Try this regex:

(?:(?<=^)|(?<=\n))\s*Parameter.*

Click to demonstrate

Explanation:

  • (?:(?<=^)|(?<=\n))- finds a position preceded only by \nor the beginning of a line
  • \s* - matches 0 + occurrences of spaces
  • Parameter.*- matches Parameterfollowed by 0+ occurrences of any character (except newline characters)
+3
source

findall:

>>> test_str = ("Parameter: A\n"
...     "%Parameter: B\n"
...     "  %  Parameter: C\n"
...     " Parameter: D %the best parameter")
>>>
>>> print filter(None, re.findall(r'%\s*Parameter|(Parameter.*)', test_str))
['Parameter: A', 'Parameter: D %the best parameter']

, , , .

- RegEx

+1

Source: https://habr.com/ru/post/1691194/


All Articles