代码之家  ›  专栏  ›  技术社区  ›  Sridhar Ratnakumar

Python中的位置匹配子字符串

  •  0
  • Sridhar Ratnakumar  · 技术社区  · 14 年前

    ['i386', 'x86_64'] 就像一根绳子 '-foo 23 -bar -arch ppc -arch i386 -isysroot / -fno-strict-aliasing -fPIC' ?

    >>> my_arch_parse_function('-foo 23 -bar -arch i386 -arch x86_64 -isysroot /  -fno-strict-aliasing -fPIC')
    >>> ['i386', 'x86_64']
    

    这可以使用regex来完成吗,或者只使用PyParsing之类的模块,或者手动拆分并迭代拆分?

    假设: -arch VAL

    6 回复  |  直到 14 年前
        1
  •  3
  •   Katriel    14 年前

    正则表达式: (?<=-arch )[^ ]+

    >>> re.findall( r"(?<=-arch )([^ ]+)", r"'-foo 23 -bar -arch ppc -arch i386 -isysroot -fno-strict-aliasing -fPIC'" )
    ['ppc', 'i386']
    

    任意空格

    >>> foo = re.compile( r"(?<=-arch)\s+[^\s]+" )
    >>> [ str.strip() for str in re.findall( foo, r"'-foo 23 -bar -arch ppc -arch i386 -isysroot -fno-strict-aliasing -fPIC'" ) ]
    ['ppc', 'i386']
    

    x86_64 -arch ppc -arch i386

        2
  •  4
  •   Marcelo Cantos    14 年前

    为什么不使用参数解析模块呢?Python2.6(和3.1)中的optparse和Python2.7(和3.2)中的argparse。

    编辑:仔细想想,这并不像听起来那么简单,因为您可能需要定义所有可能看到的参数(不确定这些模块是否有catchall机制)。我会把答案留在这里,因为可能有用,但要谨慎对待。

        3
  •  2
  •   Muhammad Alkarouri    14 年前

    你会考虑一个非正则表达式的解决方案吗?更简单:

    >>> def my_arch_parse_function(s):
    ...     args = s.split()
    ...     idxs = (i+1 for i,v in enumerate(args) if v == '-arch')
    ...     return [args[i] for i in idxs]
    ...     
    ... 
    >>> s='-foo 23 -bar -arch ppc -arch i386 -isysroot / -fno-strict-aliasing -fPIC'
    >>> my_arch_parse_function(s)
    ['ppc', 'i386']
    
        4
  •  0
  •   Sridhar Ratnakumar    14 年前

    回答我自己的问题,我找到了一个正则表达式 this tool :

    >>> regex = re.compile("(?P<key>\-arch\s?)(?P<value>[^\s]+?)\s|$")
    >>> r = regex.search(string)
    >>> r
    <_sre.SRE_Match object at 0x8aa59232ae397b10>
    >>> regex.match(string)
    None
    
    # List the groups found
    >>> r.groups()
    (u'-arch ', u'ppc')
    
    # List the named dictionary objects found
    >>> r.groupdict()
    {u'key': u'-arch ', u'value': u'ppc'}
    
    # Run findall
    >>> regex.findall(string)
    [(u'-arch ', u'ppc'), (u'-arch ', u'i386'), (u'', u'')]
    
        5
  •  0
  •   krs1    14 年前

    如果您想要正则表达式,请尝试以下操作:

    arch_regex = re.compile('\s+('+'|'.join(arch_list)+')\s+',re.I)
    results = arch_regex.findall(arg_string)
    

    对我的口味来说有点太多正则表达式了,但很管用。作为将来的参考,最好使用 optparse

        6
  •  0
  •   Hamish Grubijan    14 年前

    用蟒蛇手工制作2.6 我相信你或图书馆能做得更好。

    inp = '-foo 23 -bar -arch ppc -arch i386 -isysroot / -fno-strict-aliasing -fPIC'.split()
    dct = {}
    noneSet = set([None])
    
    flagName = None
    values = []
    for param in inp:
        if param.startswith('-'):
            flagName = param
            if flagName not in dct:
                dct[flagName] = set()
            dct[flagName].add(None)
            continue
        # Else found a value
        dct[flagName].add(param)
    
    print(dct)
    
    result = sorted(dct['-arch'] - noneSet)
    print(result)
    
    >>> ================================ RESTART ================================
    >>> 
    {'-arch': set(['ppc', 'i386', None]), '-isysroot': set([None, '/']), '-fno-strict-aliasing': set([None]), '-fPIC': set([None]), '-foo': set([None, '23']), '-bar': set([None])}
    ['i386', 'ppc']
    >>>