(?i) 和 re.sub

leetcode 345. Reverse Vowels of a String discuss 里有个解法基本是完全利用正则特性

  • 抽象出来如下
s = 'leetcode'
vowels = re.findall('(?i)[aeiou]', s)
print re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)
output:
leotcede

比较难以理解的是re.sub的用法,改成下面例子比较直观

s = 'leetcode'
vowels = ['1', '2', '3', '4']
print re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s)
output:
l43tc2d1
  • (?i)表示后面匹配的时候不区分大小写
    有四种形式
    1,(?i)
    2,(?-i)
    3,(?i:X)
    4,(?-i:X)
regex = "(?i)abcd"                                            #表示匹配abcd不区分大小写, 这道题中不区分大小写
regex = "(?i)a(?-i)bcd"   or  regex = "((?i:a)bcd"             #表示只有a不区分大小写    
  • re.sub()
Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

重点在repl上面,repl可是字符串或者函数
如果是字符串,那么将string里面所有符合pattern的全部替换成repl

如果是函数,那么对所有符合pattern的reobj都作为参数传进次对象,例如下面将所有的c,l都double

e.g
def test(x):
    a = x.group()
    string = a+a
    return string

s = 'cleetcodec'
print re.sub('(?i)[cl]', test, s)

output: cclleetccodecc

那么结合起来,re.sub('(?i)[aeiou]', lambda m: vowels.pop(), s) 就是对s里面每个符合条件的执行lambad表达式; 不过很精巧(对符合条件的元素正序进行替换,替换对象采用倒序,完成了倒转)

posted @ 2016-10-08 22:30  Salmd  阅读(778)  评论(0)    收藏  举报