1

I want to find the letters between <b> and </b> for the following string using regular expression.

s = "start<b>A</b><b>B</b><b>C</b><b>D</b>End"

The desired result is A B C D

I tried with these codes...

for i in range(4):
    r = re.search(r'.<b>.</b>.' ,"", s)
    print r

I also tried many other methods. But they all dont work.

Please dont give me minus, I understand it is a very beginners question. Thanks for your help.

2
  • print(re.findall("<b>([A-Z])<\/b>",s)) Commented Oct 20, 2016 at 18:27
  • If you want to avoid the "minus", read how to ask a question. Declaring "but they all dont work" is a prime example of how not to ask a question. Commented Oct 20, 2016 at 18:36

4 Answers 4

1

Use re.findall to find all occurrences of a regex that includes <b>, the intermediate characters, and </b>:

import re
s = "start<b>A</b><b>B</b><b>C</b><b>D</b>End"

for match in re.findall(r'<b>(.*?)</b>', s):
    print match,

The parentheses in the regex serve to create a group, telling findall that you are interested in the stuff between <b> and </b>.

The .*? part of the regular expression means match zero or more characters, preferring the smallest string that satisfies the expression.

Sign up to request clarification or add additional context in comments.

Comments

1

Here is a sample regex that will match

>>> import re
>>> p = re.compile(r'<b>(.+?)</b>')
>>> p.findall("start<b>A</b><b>B</b><b>C</b><b>D</b>End")
['A', 'B', 'C', 'D']

Comments

0

Use the re.findall function.

>>> m = re.findall(r'<b>(.+?)</b>', s)
>>> m
['A', 'B', 'C', 'D']

>>> ' '.join(m)
'A B C D'

Comments

0

Since this is XML you are parsing (at least it looks like), why don't use an XML parser, like the xml.etree.ElementTree from the Python standard library:

In [1]: import xml.etree.ElementTree as ET

In [2]: s = "start<b>A</b><b>B</b><b>C</b><b>D</b>End"

In [3]: root = ET.fromstring("<root>%s</root>" % s)

In [4]: [b.text for b in root.findall("b")]
Out[4]: ['A', 'B', 'C', 'D']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.