python - 正则表达式 : Find Names in String using Python

标签 python html regex html-parsing

到目前为止,我在使用正则表达式时从未遇到过困难。我希望解决方案不是很明显,因为我可能已经在这个问题上花了几个小时。

这是我的字符串:

<b>Carson Daly</b>: <a href="https://rads.stackoverflow.com/amzn/click/com/B009DA74O8" rel="nofollow noreferrer">Ben Schwartz</a>, Soko, Jacob Escobedo (R 2/28/14)<br>'

我想将“Soko”和“Jacob Escobedo”提取为单独的字符串。如果我采用两种不同的提取模式,这对我来说没有问题。

我已经尝试过“\s([A-Za-z0-9]{1}.+?)”和该正则表达式的其他更改来获取我想要的数据,但我没有成功。感谢您的帮助。

名称从不遵循相同的标签或相同的符号。唯一始终位于名称前面的是空格 (\s)。

这里以另一个字符串为例:

<b>Carson Daly</b>: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh<br>

最佳答案

另一种方法是使用 HTML 解析器解析字符串,例如 lxml .

例如,您可以使用 xpath 查找包含 Carson Daly 文本的 b 标签和 br 标签之间的所有内容,方法是检查 precedingfollowing sibling :

from lxml.html import fromstring

l = [
    """<b>Carson Daly</b>: <a href="http://rads.stackoverflow.com/amzn/click/B009DA74O8">Ben Schwartz</a>, Soko, Jacob Escobedo (R 2/28/14)<br>'""",
    """<b>Carson Daly</b>: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh<br>"""
]

for html in l:
    tree = fromstring(html)
    results = ''
    for element in tree.xpath('//node()[preceding-sibling::b="Carson Daly" and following-sibling::br]'):
        if not isinstance(element, str):
            results += element.text.strip()
        else:
            text = element.strip(':')
            if text:
                results += text.strip()

    print results.split(', ')

它打印:

['Ben Schwartz', 'Soko', 'Jacob Escobedo (R 2/28/14)']
['Wil Wheaton', 'the Birds of Satan', 'Courtney Kemp Agboh']

关于python - 正则表达式 : Find Names in String using Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24091237/

相关文章:

javascript - 正则表达式在多行文本中下一个匹配的开头处停止

python - Opencv:好的点匹配,但单应性错误

python - 在 Python 中从字节字符串中删除前 20 个字节的最快方法是什么?

javascript - 如何使用 DOM 查找表格的列数?

android - 如何调整视口(viewport)大小和缩放以支持跨浏览器?

regex - 如何在正则表达式中允许使用任何字符?

python - 从列表中查找 pandas 列与另一列的唯一组合

python - 将类的实例(类的对象)传递给另一个类

javascript - ReactJS + Webpack : Why Uncaught Error: Cannot find module "../media/interiorTest.jpg"?

javascript - javascript 中的正则表达式问题