zara
zara

Reputation: 385

Using Python Regex with Line Count

This is my test code:

\thinhline
\\[-16pt]
Jacobi
  & $\JacobiP{\alpha}{\beta}{n}@{x}$
  & $(-1,1)$
  & $(1 - x)^{\alpha} (1 + x)^{\beta}$
  & $\begin{cases} \ifrac{2^{\alpha+\beta+1}\EulerGamma@{\alpha+1}\EulerGamma@{\beta+1}}{\EulerGamma@{\alpha+\beta+2}}, &\text{$n = 0$} \end{cases}$
  & $\begin{cases} \ifrac{2^{\alpha+\beta+1}\EulerGamma@{\alpha+1}\EulerGamma@{\beta+1}}{\EulerGamma@{\alpha+\beta+2}}, & \text{$n = 0$}\end{cases}$
  & $\dfrac{\pochhammer{n+\alpha+\beta+1}{n}}{2^n n!}$
  & $\dfrac{n (\alpha-\beta)}{2n+\alpha+\beta}$
  & $\alpha,\beta > -1$

  \\
\thinhline
\\[-16pt]
Ultraspherical(Gegenbauer)
  & $\Ultraspherical{\lambda}{n}@{x}$
  & $(-1,1)$
  & $(1 - x^2)^{\lambda-\frac{1}{2}}$
  & $\dfrac{2^{1-2\lambda} \pi \EulerGamma@{n+2\lambda}}
           {(n+\lambda) \left( \EulerGamma@{\lambda} \right)^2 n!}$
  & $\dfrac{2^n \pochhammer{\lambda}{n}}{n!}$ & $0$
  & $\lambda > -\tfrac{1}{2}, \lambda \ne 0 $
\\

I have created a pattern to identify the pattern of everything in between "\thinhline \\[-16pt]" and "\\".

How would I find the line count of the lines beginning with ampersands, "&", of the instance of the pattern found?

For example I would want this returned for the sample code:

Jacobi: 8
Ultraspherical(Gegenbauer): 6

Upvotes: 2

Views: 88

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 113940

for i,line enumerate(my_text.splitlines(),1):
    if line.strip().startswith("&"):
       print line,"On line",i

might be what you want ... I dont think regex is the right answer for this

Upvotes: 1

eddi
eddi

Reputation: 49448

How about:

import re

s = text.split('\\thinhline\n\\\\[-16pt]\n')[1:]
res = [re.split("\n\s*&", a) for a in s]

[a[0] + ": " + str(len(a)-1) for a in res]
#['Jacobi: 8', 'Ultraspherical(Gegenbauer): 6']

Upvotes: 1

Try this regex ^\s*& with the MULTILINE (re.M) flag:

import re

text = """
  & $\Ultraspherical{\lambda}{n}@{x}$
  & $(-1,1)$
  & $(1 - x^2)^{\lambda-\frac{1}{2}}$
  & $\dfrac{2^{1-2\lambda} \pi \EulerGamma@{n+2\lambda}}
           {(n+\lambda) \left( \EulerGamma@{\lambda} \right)^2 n!}$
  & $\dfrac{2^n \pochhammer{\lambda}{n}}{n!}$ & $0$
  & $\lambda > -\tfrac{1}{2}, \lambda \ne 0 $

"""

print(len(re.findall('^\s*&', text, re.M)))

prints 6, which is the number of lines beginning with &

Upvotes: 1

Related Questions