【问题标题】:re.compile not matching my stringre.compile 与我的字符串不匹配
【发布时间】:2015-01-05 21:28:36
【问题描述】:

这是我的代码:

def split(content):
   pattern = re.compile(r"""(\\\[-16pt]\n)(.*?)(\n\\\nthinhline)""", re.X | re.DOTALL)
   print(pattern.finditer(content))
   for m in pattern.finditer(content):
       print ("in for loop")
       print("Matched:\n----\n%s\n----\n" % m.group(2))
   print ("in split")


def replacement(content):
   split(content)
   pattern = re.compile(r'(?<=\\\\\[-16pt]\n)([\s\S]*?)(?=\\\\\n\\thinhline)')
   content= ' '.join(re.findall(pattern, content))
   print ("in replace")
   return content

这是输出:

<callable-iterator object at 0x2ab2e09cfe10>
in split
in replace

我用不同的字符串尝试了算法,它工作正常。我还测试了内容是否是字符串,并且确实如此。为什么程序进入了 split() 却没有进入 for..loop?

谢谢。

【问题讨论】:

  • 你想做什么?我 100% 确定 re.compile 中没有错误。
  • @MarounMaroun stackoverflow.com/questions/27745894/… 这就是我想要做的,但文本要大得多。
  • 如果删除print(pattern.finditer(content))会怎样?
  • 您的字符串根本不匹配。 “打印('in split')”在循环之外......
  • 如果您发布一个完整的、可运行的程序来显示问题,它会另外提供帮助。我在回答你原来的问题时这样做了。您不必发布 真正的 完整可运行程序,但您可以使用真实输入(尽管小于完整输入)和 main 将其删减,因此我们可以将其复制/粘贴/运行到看到你的问题。通常,解决这个问题有助于向您揭示问题。

标签: python regex python-2.7


【解决方案1】:

见 cmets:

def split(content):
   pattern = re.compile(r"""(\\\[-16pt]\n)(.*?)(\n\\\nthinhline)""", re.X | re.DOTALL)

   # the message you're seeing is correct - this line prints an iterator object -
   # like all iterators, you must actually iterate over it to see the iterator's
   # contents. You're seeing the string representation of an iterator, not the
   # iterator's contents.
   print(pattern.finditer(content))

   # this will iterate over the match objects in the iterator object - but there
   # is no guarantee that any exist
   for m in pattern.finditer(content):
       print ("in for loop")
       print("Matched:\n----\n%s\n----\n" % m.group(2))

   # now you're printing this string, which you correctly observed - note that it is
   # outside of the for loop. This means that its execution is not dependent on the 
   # regex actually finding any matches.
   print ("in split")

由于从未打印过“in for loop”,这意味着您的正则表达式从未匹配。我使用Python Regex Tool 网站调试我的正则表达式取得了很好的成功。尝试在一些示例文本上使用该网站,以确保您的正则表达式实际上与您期望的位置匹配。

您当前的问题只是您的正则表达式没有找到任何匹配项。

【讨论】:

  • @mbomb007 哦……我以前没见过那个网站。我也喜欢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多