Brian Putt
Brian Putt

Reputation: 1348

python regex comma separated group

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)

Upvotes: 0

Views: 766

Answers (2)

falsetru
falsetru

Reputation: 369134

>>> 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

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174706

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']

Upvotes: 0

Related Questions