2014-11-05 27 views
0

我很难理解Python中的正则表达式。用Python中的正则表达式搜索

else: 
    #REGEX1 
    ret = re.search(r'name:(?P<scname>)',line) 
    if(ret != None): 
     print('The name is'+ret.group("scname")) 
    else: 
    #REGEX2 
    ret = re.search(r'(?P<content>)',line) 
    print('The content is'+ret.group("content")) 

我解析一个文本文件,内容如下

name:english 
1001Nights 
A Night at the Call Center 
Grammar 
name:science 
Engineering 
Biology 
Physics 
name:maths 
Algebra 
Geometry 

我所要的输出是

名称是英文
内容是1001Nights
内容是在呼叫中心的夜晚
内容为语法
姓名为sc ience
内容是工程
内容是生物学

请帮我纠正我的正则表达式,并建议任何链接更容易理解正则表达式。 的官方文档感觉有点不知所措,因为我是新来的Python

UPDATE

这是我的错误,如果它可以帮助

The subclient name is 
Traceback (most recent call last): 
    File "create&&bkp.py", line 32, in <module> 
    print('The subclient name is'+ret.group("scname")) 
IndexError: no such group 

回答

2
ret = re.search(r'name:(?P<scname>)',line) 

此搜索'name:'在某一行(不一定在开头),如果找到,则在冒号后面的位置产生一个匹配对象。由于>和)之间没有任何内容,因此该组为空,但名称为scname。因此,您显示的代码段与错误不匹配。其他不匹配包括在错误之前打印字符串的一部分以及单词“subclient”。

我会考虑简单的字符串处理:

for line in lines: 
    line=line.rstrip('\n') # assuming it came from a file, remove newline 
    if line.startswith('name:'): 
     print('The name is '+line[len('name:'):]) 
    else: 
     print('The content is '+line) 

它也可以做到使用正则表达式的整个分类:

matcher=re.compile(r'^(name:(?P<name>.*)|(?P<content>.*))$') 
for line in lines: 
    m=matcher.match(line) 
    for key,value in m.groupdict(): 
     if value is not None: 
      print('The {} is {}'.format(key,value)) 
0
(?<=:)(.*)$ 

这将是你的regex1看演示。

http://regex101.com/r/iZ9sO5/8

^(?!.*?:)(.*)$ 

这将是你的regex2.See演示。

http://regex101.com/r/iZ9sO5/9

+0

感谢。将检查出来,让你知道:) :) – 2014-11-05 11:30:02

+0

文件“创建&& bkp。py“,第27行 ret = re.search((?<=:)(。*)$,line) ^ SyntaxError:无效的语法 – 2014-11-05 12:07:22

1

你并不需要一个正则表达式,如果你的文件在公布的格式:

with open("in.txt") as f: 
    for line in f: 
     if "name:" in line: 
      print("The name is {}".format(line.rstrip().split("name:",1)[1])) 
     else: 
      print("The content is {}".format(line.rstrip())) 

输出:

The name is english 
The content is 1001Nights 
The content is A Night at the Call Center 
The content is Grammar 
The name is science 
The content is Engineering 
The content is Biology 
The content is Physics 
The name is maths 
The content is Algebra 
The content is Geometry 
+0

谢谢@Padraic,但基于正则表达式的搜索更强大的权利?该内容的名称中有“:”?:) – 2014-11-05 12:04:07

+0

它不会有什么区别,我们只在行中包含字符串'name:'时才分割 – 2014-11-05 12:05:51

0
else: 
    #REGEX1 
    ret = re.search(r'name:(.*)$',line) 
    if(ret != None): 
     print('The name is'+ret.group(1)) 
    else: 
     #REGEX2 
     # ret = re.search(r'(?P<content>)',line) 
     print('The content is'+line))