首页 > 代码库 > python 正则表达式 匹配指定字符遇到问题记录

python 正则表达式 匹配指定字符遇到问题记录

匹配1, 12 ,234

 

错误的例子:

import re
line = "prediction correct 1 >>>>>>>>>>>>>>>>>>>>!real class: 12, predicted class:234 ";
pattern = re.compile(r‘.*real class.*(\d*).*predicted class.*(\d*).*‘)
match_obj = re.search(pattern,line)
print match_obj.groups()

 

 

 

 

 

import re
line = "prediction correct 1 >>>>>>>>>>>>>>>>>>>>!real class: 12, predicted class:234 ";
pattern = re.compile(r‘prediction correct.*([0-9]\d*).*real class.*([0-9]\d*).*predicted class.*([0-9]\d*).*‘)
match_obj = re.search(pattern,line)
print match_obj.group()
print match_obj.group(1)
print match_obj.group(2)

 

 

正确的结果:

import re
line = "prediction correct 1 >>>>>>>>>>>>>>>>>>>>!real class: 12, predicted class:234 ";
pattern = re.compile(r‘prediction correct.*([0-9]\d*).*real class.*?([0-9]\d*).*predicted class.*?([0-9]\d*).*‘)
match_obj = re.search(pattern,line)
print match_obj.group()
print match_obj.group(1)
print match_obj.group(2)

 

 

问题:

1.为什么要加【0-9】

2.注意?的使用,仔细理解

 

python 正则表达式 匹配指定字符遇到问题记录