-2

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.

Foklan
  • 11
  • 2
  • Could you solve this by looping over each line, and checking `line.startswith('#')` to ignore commented lines? – Nick ODell Feb 27 '23 at 16:00
  • @NickODell Unfortunately not, I need to match it on place with single regex without any additional code. – Foklan Feb 27 '23 at 16:04
  • Why do you **need** to use a regular expression when it's absolutely not necessary for the required functionality. Homework perhaps? – DarkKnight Feb 27 '23 at 16:09

2 Answers2

0

Given the required functionality and no reasonable explanation for the need to use re then it's as simple as:

with open('/etc/fstab') as fstab:
    for line in fstab:
        fs_spec, _, _, fs_mntops, *_ = line.split()
        if not fs_spec.startswith('#'):
            print(fs_mntops)
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

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

Nick ODell
  • 15,465
  • 3
  • 32
  • 66