如何在正则表达式中完成特定数字的查找

(本文的例子使用python完成)

参考:Python正则表达式操作指南 http://wiki.ubuntu.org.cn/Python%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%93%8D%E4%BD%9C%E6%8C%87%E5%8D%97

 

如何使用正则表达式查找出"abc = 128"这个字符串中的数字呢?

可以使用命名组功能来完成,以下这个例子,仅供想学习正则表达式的同学入门使用。

line = "abc = 128"

p = re.compile(r'abc = (?P<num>/d*)')

m = p.search(line)

m.group('num')



print "--============= named group ==============--"

line = "test it: abc = 64, def = 128"

p = re.compile(r'abc = (?P<num>/d*), def = (?P<num2>/d*)')

m = p.search(line)

print "group 1 = ", m.group('num')

print "group 2 = ", m.group('num2')



print "--============= named group 2 ==============--"

line = "test it: abc = 64, def = (128), ghi = [123]"

p = re.compile(r'abc = (?P<group1>/d+), def = /((?P<group2>/d*)/), ghi = /[(?P<group3>/d*)/]')

m = p.search(line)

print "group 1 = ", m.group('group1')

print "group 2 = ", m.group('group2')

print "group 3 = ", m.group('group3')

你可能感兴趣的:(c,python,正则表达式)