Python:在第一次出现两个子串之间找到一个字符串

TJ1*_*TJ1 0 python regex python-2.7

我有这样的文字:

text='gn="right" headers="gr-Y10 gr-eps i36">121.11<\\/td><\\/tr><tr class="hr"><td colspan="12"><\\/td><\\/tr><tr>'
Run Code Online (Sandbox Code Playgroud)

我想从中121.11使用正则表达式来获取值.所以我这样做了:

import re
b=re.search('gr-Y10 gr-eps i36">(.*)<\\\\/td', text)
b.group(1)
Run Code Online (Sandbox Code Playgroud)

我把它作为输出:

'121.11<\\/td><\\/tr><tr class="hr"><td colspan="12">'
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到我真正想要的东西,而121.11不是上面的那一行?

vks*_*vks 6

gr-Y10 gr-eps i36">(.*?)<\\\\/td

                      ^^
Run Code Online (Sandbox Code Playgroud)

*通过附加来使你的非贪婪?.通过使它非贪婪,它会在第一个实例中停止<\\\\/td它将最后捕获<\\\\/td.

见演示.

https://regex101.com/r/iS6jF6/2#python


ale*_*cxe 5

知道了输入数据的源,并考虑到它是HTML,这里是涉及一种的溶液HTML解析器BeautifulSoup

soup = BeautifulSoup(input_data)

for row in soup.select('div#tab-growth table tr'):
    for td in row.find_all('td', headers=re.compile(r'gr-eps')):
        print td.text
Run Code Online (Sandbox Code Playgroud)

基本上,对于“增长”表中的每一行,我们都会找到带有gr-eps标题的单元格(表的“EPS %”部分)。它打印:

60.00
—
—
—
—
42.22
3.13
—
—
—
-498.46
...
Run Code Online (Sandbox Code Playgroud)

这也是一本好书

  • @TJ1 感谢您通过提供正则表达式主题的非正则表达式答案让我更接近正则表达式银徽章:) (2认同)