re.compile不匹配我的字符串

2024-09-30 18:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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

输出如下:

^{pr2}$

我用不同的字符串尝试了这个算法,效果很好。我还测试了内容是否是一个字符串。为什么程序没有进入for..循环,即使它正在进入split()?在

谢谢。在


Tags: 字符串代码inreloopfordefcontent
1条回答
网友
1楼 · 发布于 2024-09-30 18:25:06

见评论:

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网站调试正则表达式取得了很好的成功。尝试在一些示例文本中使用该网站,以确保您的regex实际上与您期望的位置匹配。在

您当前的问题很简单,您的正则表达式找不到任何匹配项。在

相关问题 更多 >