Yuiry Kozlenko
Yuiry Kozlenko

Reputation: 665

Identify multiple regex matches in a single string and get substring for each match

I would like to find strings with regex pattern. For example:

# header ## smaller header

I would like to find two string set as follows.

# header
## smaller header

So I make the regex pattern as follows.

pattern = re.compile("(?:^#+|\s#+)\s")

With this pattern, I can find # header.

# header

But I can't find the string such as ## smaller header

How can I make the regex so that find two set of strings?

Upvotes: 0

Views: 753

Answers (2)

Nick Chapman
Nick Chapman

Reputation: 4634

You can do the following

import re
p = re.compile(r"#+(\s\w+)+")
for m in p.finditer('# header ## smaller header'):
    print(m.group())

which outputs

# header 
## smaller header

Upvotes: 2

Kaushik Nayak
Kaushik Nayak

Reputation: 31656

       import re
       pattern = re.compile("#+[\s\w]+")
       a = re.findall(pattern,'# header ## smaller header')
       print (*a,sep="\n")

Upvotes: 1

Related Questions