用Python搜索Regex

2024-04-25 06:18:56 发布

您现在位置: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

我希望输出是

名称为英文
内容为1001晚
内容是在呼叫中心过夜
内容是语法
名字叫科学
内容是工程
内容是生物学

请帮助我纠正我的正则表达式,并建议任何链接,以了解正则表达式更容易。 由于我是Python新手,官方文档让人感觉有点难以理解

更新

这是我得到的错误,如果有帮助的话

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

Tags: thenamere内容searchislinegroup
3条回答
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)

也可以使用regex进行整个分类:

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))
(?<=:)(.*)$

这将是您的regex1。请参阅演示。你知道吗

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

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

这将是您的regex2。请参阅演示。你知道吗

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

如果文件的格式为:

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

相关问题 更多 >