0

I have a string that I am trying to create a group of only the items that have commas. So far, I am able to create a group, what I'm trying to do is ensure that the string contains the word nodev. If the string doesn't contain that word, a match should show, otherwise, the regex should not match anything.

String:

"/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async    1  2"

Regex that matches the comma delimited group:

([\w,]+[,]+\w+)

I've tried this regex but with no luck:

(?!.*nodev)([\w,]+[,]+\w+)

I'm using https://pythex.org/ and am expecting my output to have one match that contains "rw,exec,auto,nouser,async". This way I plan on appending ,nodev to the end of the string if it doesn't contain it.

Looking for a regex only solution(no functions)

8
  • What's your expected output? Commented Sep 23, 2014 at 13:48
  • I'm using pythex.org and am expecting my output to have one match that contains "rw,exec,auto,nouser,async" Commented Sep 23, 2014 at 13:49
  • Isn't string.split()[3] enough? Commented Sep 23, 2014 at 13:51
  • Looking for a regex only solution with no functions Commented Sep 23, 2014 at 13:51
  • 1
    \s([a-z]+,[a-z,]+)\s Commented Sep 23, 2014 at 13:54

2 Answers 2

2
>>> import re
>>> s = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async    1  2"
>>> s2 = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nodev,nouser,async    1  2"
>>> re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s)
['rw,exec,auto,nouser,async']
>>> re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s2)
[]

To append ,nodev:

>>> re.sub(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', r'\g<0>,nodev', s)
'/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async,nodev    1  2'
>>> re.sub(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', r'\g<0>,nodev', s2)
'/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nodev,nouser,async    1  2'

pythex demo

Sign up to request clarification or add additional context in comments.

2 Comments

i think it won't work if both comma seperated values are present within a single string variable.
@AvinashRaj, I think the string came from fstab. So it will have one options field (rw,exec,auto,nouser,async) per line.
0

Complete regex solution.

For this to work, you need to import regex module.

>>> import regex
>>> s = " /dev/mapper/ex_s-l_home /home  ext4 rw,exec,auto,nouser,async    1  2 rw,exec,nodev,nouser,async    1  2 nodevfoo bar"
>>> m = regex.findall(r'(?<=^|\s)\b(?:(?!nodev)\w+(?:,(?:(?!nodev)\w)+)+)+\b(?=\s|$)', s)
>>> m
['rw,exec,auto,nouser,async']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.