【问题标题】:Regular expression not behaving as expected正则表达式未按预期运行
【发布时间】:2012-10-15 01:51:29
【问题描述】:

我有以下函数,它应该读取.html 文件并搜索<input> 标签,并将<input type='hidden'> 标签注入要显示在页面中的字符串中。 但是,这个条件永远不会满足:(例如,if 语句永远不会执行。)我的正则表达式有什么问题?

 def print_choose( params, name ):

   filename = path + name
   f = open( filename, 'r' )
   records = f.readlines()
   print "Content-Type: text/html"
   print
   page = ""
   flag = True
   for record in records:
        if re.match( '<input*', str(record) ) != None:
            print record
            page += record
            page += "<input type='hidden' name='pagename' value='psychology' />"
        else:
            page += record

   print page

谢谢

【问题讨论】:

    标签: python html regex


    【解决方案1】:

    re.match 从字符串中的第一个字符开始。你确定不想要re.search,它可以匹配字符串中间的模式吗?

    【讨论】:

      【解决方案2】:
         if re.match( '<input*', str(record) ) != None:
      

      你可能想要&lt;input.*。现在你会匹配&lt;inputttttttttt,但不会匹配&lt;input&gt;blahblah. 表示任意字符,* 表示 0 或匹配正则表达式中的最后一项,因此 .* 要求在 0 个或多个字符上重复通配符匹配。

      (PS 检查regexpal 进行正则表达式调试)

      【讨论】:

      • 这是真的,但不是他的if 没有被触发的原因。
      • @DSM 可能是因为柯克的回答。
      • @DougT.:是的,当我复制粘贴文档时,他打败了我。 :^)
      • @DSM 我是夜贼。
      猜你喜欢
      • 2014-04-15
      • 2014-04-28
      • 2022-01-02
      相关资源
      最近更新 更多