2014-09-23 221 views
0

我有一个字符串,我试图创建一组只有有逗号的项目。到目前为止,我可以创建一个组,我试图做的是确保该字符串包含word nodev。如果字符串不包含该单词,则应显示匹配,否则,正则表达式不应匹配任何内容。python正则表达式逗号分隔组

字符串:

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

正则表达式的逗号分隔小组赛:

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

我已经试过这正则表达式,但没有运气:

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

我使用https://pythex.org/,并期望我的输出有一个包含“rw,exec,auto,nouser,async”的匹配项。这样我计划追加,nodev到字符串的末尾,如果它不包含它。

寻找一个正则表达式唯一的解决办法(无功能)

+0

您的预期产出是? – 2014-09-23 13:48:47

+0

我正在使用https://pythex.org/,期待我的输出有一个包含“rw,exec,auto,nouser,async”的匹配项 – 2014-09-23 13:49:47

+0

不是'string.split()[3]'足够多? – falsetru 2014-09-23 13:51:01

回答

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) 
[] 

要追加,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

+0

我认为这不会工作,如果两个逗号分隔值存在于一个字符串变量。 – 2014-09-23 14:20:53

+0

@AvinashRaj,我想这个字符串来自['fstab'](http://en.wikipedia.org/wiki/Fstab)。所以每行有一个选项字段('rw,exec,auto,nouser,async')。 – falsetru 2014-09-23 14:25:48

+0

pythex演示非常有帮助,谢谢! – 2014-09-23 18:03:09

0

完整的正则表达式的解决方案。

为此,您需要导入regex模块。

>>> 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'] 
相关问题