簡體   English   中英

Python正則表達式-TypeError

[英]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之間的所有內容都匹配的模式?

我在Regex101.com上測試了您的正則表達式,看來它由於多種原因而失敗。 首先,點. 不適用於換行符,因此它在第一個換行符處停止。 其次,我認為您必須在最后一部分\\n\\\\\\n\\\\\\thinhline上使用許多斜線。 它轉義了t ,因此它正在尋找一個制表符。 這個正則表達式為我工作: (\\\\\\[-16pt]\\n)(.|\\s)*?(\\\\thinhline)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM