Search code examples
regexpcre

Match pam file lines


I would like to parse pam files with the following two examples and look for deny configuration.

auth    required     pam_faillock.so authsucc deny=4 even_deny_root unlock_time=1200
auth    required     pam_faillock.so authsucc even_deny_root unlock_time=1200

The pattern should match both lines:

1 Line Match should return group1 "deny=4" and group2 "4"

2 Line Match should return empty group1 and empty group2

(^auth\s+required\s+pam_faillock\.so).*?(?(1) (deny\=(\d+))|(.*))

Solution

  • You can use

    ^auth\s+required\s+pam_faillock\.so\s(?|.*?(deny=(\d*))|()())?
    

    Details:

    • ^auth\s+required\s+pam_faillock\.so - auth required pam_faillock.so string where the spaces can be one or many
    • \s - a single whitespace
    • (?|.*?(deny=(\d*))|()())? - an optional branch reset group that matches
      • .*?(deny=(\d*)) - any zero or more chars other than line break chars as few as possible, then a Group 1 that captures deny= + zero or more digits that are themselves captured into Group 2
      • | - or
      • ()() - Group 1 and 2 that contain empty strings.

    See the regex demo.