当前位置: 首页 > 面试题库 >

Python-如何在string.replace中输入正则表达式?

丌官星渊
2023-03-14
问题内容

我需要一些帮助来声明正则表达式。我的输入如下:

this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>

所需的输出是:

this is a paragraph with in between and then there are cases ... where the number ranges from 1-100. 
and there are many other lines in the txt files
with such tags

我已经试过了:

#!/usr/bin/python
import os, sys, re, glob
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
    for line in reader: 
        line2 = line.replace('<[1> ', '')
        line = line2.replace('</[1> ', '')
        line2 = line.replace('<[1>', '')
        line = line2.replace('</[1>', '')

        print line

我也尝试过此方法(但似乎我使用了错误的regex语法):

    line2 = line.replace('<[*> ', '')
    line = line2.replace('</[*> ', '')
    line2 = line.replace('<[*>', '')
    line = line2.replace('</[*>', '')

我不想replace从1到99 进行硬编码。。。


问题答案:

这个经过测试的代码段应该做到这一点:

import re
line = re.sub(r"</?\[\d+>", "", line)

编辑:这是一个注释的版本,说明其工作方式:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

正则表达式很有趣!但我强烈建议你花一两个小时来学习基础知识。对于初学者,你需要了解哪些特殊字符:需要转义的“元字符”(即,前面加反斜杠-字符类的内外规则是不同的。)在以下位置有一个出色的在线教程:www .regular-expressions.info。你在那里度过的时间将使自己获得很多倍的回报。



 类似资料:
  • 问题内容: 有没有办法在Python中调试正则表达式?而且我不是指尝试和尝试直到他们起作用的过程:) 这是在Perl中调试正则表达式的方式: 上面的代码在运行时在我的计算机上产生以下输出: 问题答案: p = re.compile(‘.*’, re.DEBUG) max_repeat 0 65535 any None >>>

  • 问题内容: 我想在内部使用,该怎么办Python? 问题答案: 从python 3.6开始,你还可以使用文字字符串插值。在你的特定情况下,解决方案是:

  • 问题内容: 在Python中使用正则表达式,如何验证用户密码为: 至少8个字符 必须限制于,但不特别要求以下任何一项: 大写字母:AZ 小写字母:az 数字:0-9 任何特殊字符:@#$%^&+ = 注意,所有字母/数字/特殊字符都是可选的。我只想验证密码长度至少为8个字符,并且限制为字母/数字/特殊字符。用户可以选择使用强弱密码。到目前为止,我所拥有的是: 问题答案: 的意思是“至少8”。该函数

  • 如何简化这个正则呢? 或者是否有其他实现方式(正则)?

  • 问题内容: 我正在Google App Engine上构建应用程序。我是Python的新手,在过去3天里,我一直对下面的问题problem之以鼻。 我有一个代表RSS Feed的类,在这个类中,我有一个名为setUrl的方法。输入此方法的是URL。 我正在尝试使用re python模块来验证RFC 3986 Reg- ex(http://www.ietf.org/rfc/rfc3986.txt)

  • 如何在不包含连续子字符串baa的字母表{a,b,c}上表达正则表达式?