Python Regex- TypeError

时间:2015-01-02 20:15:33

标签: python regex typeerror

我写了以下函数:

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

函数调用:

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

内容是一个字符串。

当我在一个单独的程序中尝试该函数的内容时,它工作正常但在这里它无法进入循环并且在进一步检查时 - re.compile语句不能用于尝试打印模式出现以下错误:

TypeError: expected string or buffer

编辑:

import re

content = """ iaisjifgrhjoigehtoi w \\
\thinhline
\\[-16pt]
  Ultraspherical
\\
\thinhline
\\[-16pt]
  & $0$
  &
\\
\thinhline
\\[-16pt]
  & $\tfrac{1}{2} \pi$
  & $2^n$
  & $0$
  &
\\
\thinhline
\\[-16pt]
  & $\tfrac{1}{2}$
  &
\\
\thinhline
\\[-16pt]
  & $(-1,1)$ & $(1 - x)^{-\frac{1}{2}} (1 + x)^{\frac{1}{2}}$
  & $\pi$
  & $-\tfrac{1}{2}$
\\
\thinhline
\\[-16pt]
  & $(0,1)$
  & $(x - x^2)^{-\frac{1}{2}}$
  & $\begin{cases} 2^{2n-1}, &\text{$n > 0$} \\ 1, &\text{$n = 0$} \end{cases}$
  & $-\tfrac{1}{2} n$
  &
\\
\thinhline
\\[-16pt]
  \begin{minipage}[c]{1.2in}\centering Shifted Chebyshev\\of second kind\end{minipage}
  &
\\
\thinhline
\\[-16pt]
  Legendre
\\
\thinhline
\\[-16pt]
  Shifted Legendre
\\
\thinhline
\\[-16pt]
  Laguerre
\\
\thinhline
\\[-16pt]
  Hermite
\\
\thinhline
\\[-16pt]
  Hermite
\\
\thinhline
\end{tabular}
\end{table}
\end{landscape}
%
\end{onecolumn*}
"""
pattern = re.compile(r"""(\\\[-16pt]\n)    # Start. Don't technically need to capture.
                             (.*?)             # What we want. Must capture ;)
                             (\n\\\n\\\thinhline) # End. Also don't really need to capture
                          """, re.X | re.DOTALL)

for m in pattern.finditer(content):
    print("Matched:\n----\n%s\n----\n" % m.group(1))

显然,模式不匹配,为什么?我如何制作一个与\ [ - 16pt]和\ \ thinhline之间的所有内容相匹配的模式?

1 个答案:

答案 0 :(得分:0)

我在Regex101.com上测试了你的正则表达式,似乎它失败了很多原因。首先,点.不适用于换行符,因此它在第一个换行符时停止。其次,我认为你在最后一部分\n\\\n\\\thinhline上有很多斜线。它正在逃避t,所以它正在寻找制表符。这个正则表达式对我有用:(\\\[-16pt]\n)(.|\s)*?(\\thinhline)