【问题标题】:python regex comma separated grouppython 正则表达式逗号分隔组
【发布时间】:2014-09-23 13:47:02
【问题描述】:

我有一个字符串,我正在尝试创建一组仅包含逗号的项目。到目前为止,我能够创建一个组,我要做的是确保字符串包含单词 nodev。如果字符串不包含该单词,则应显示匹配项,否则,正则表达式不应匹配任何内容。

字符串:

"/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 附加到字符串的末尾。

寻找仅正则表达式的解决方案(无函数)

【问题讨论】:

  • 你的预期输出是什么?
  • 我正在使用 pythex.org 并希望我的输出有一个包含“rw,exec,auto,nouser,async”的匹配项
  • string.split()[3] 还不够吗?
  • 寻找没有功能的仅正则表达式解决方案
  • \s([a-z]+,[a-z,]+)\s

标签: python regex


【解决方案1】:
>>> 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

【讨论】:

  • 我认为如果两个逗号分隔值都存在于单个字符串变量中,它将不起作用。
  • @AvinashRaj,我认为字符串来自fstab。因此每行将有一个选项字段 (rw,exec,auto,nouser,async)。
【解决方案2】:

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

为此,您需要导入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']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2013-12-28
    相关资源
    最近更新 更多