Search code examples
pythonpython-3.xregexpython-re

I'm unable to write regular expression for capturing mount options from fstab


I'm trying capture mount options in fstab config with python regex module for /tmp LV.

This is how the config looks like:

/dev/mapper/rootvg-lv_home    /home          ext4    nosuid,nodev        1 2
/dev/mapper/rootvg-lv_opt     /opt           ext4    nosuid,nodev        1 2
#/dev/mapper/rootvg-lv_tmp     /tmp           ext4    nosuid,noexec       1 2
/dev/mapper/rootvg-lv_tmp     /tmp           ext4    nosuid,nodev        1 2
/dev/mapper/rootvg-lv_var     /var           ext4    nosuid,nodev        1 2

So I need to capture only options "nosuid,nodev" from this line:
/dev/mapper/rootvg-lv_tmp /tmp ext4 nosuid,nodev 1 2

I tried this:
(?<=\s+\/tmp\s+ext4\s+)(\,|[a-z])+(?=\s+[0-9])

But it also caputures commented line.
Even worse python re module can't run this regex expression because of this problem with lookbehind The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not.
-source: https://docs.python.org/3/library/re.html

If I try to run it with current regex this error will popup
look-behind requires fixed-width pattern

How should I construct regex expression for this?

Very important, I can't use any other module than re!

I visited a few sites such as:
Python regex error: look-behind requires fixed-width pattern Python Regex Engine - "look-behind requires fixed-width pattern" Error

But I wasn't able to construct anything that would work for my kind of problem.


Solution

  • How about a regex like this?

    ^[^\s#]+\s+/tmp\s+\S+\s+(\S+)
    

    No lookaround, matches only /tmp, and captures the options into group 1. Avoids matching the commented line by saying that the first field may contain any character which is not whitespace or #.

    https://regex101.com/r/rK8rLA/1