2017-05-18 1 views
0

'alt'태그의 따옴표 사이에 텍스트를 가져 오는데 어려움을 겪고 있습니다. 나는 그것을 건너 뛰기 위해 [!? border = "0"]과 같은 정규식을 시도해 왔지만 여전히 효과가 없을 것이다.몇 마디 건너 뛰는 정규식

내가 \s(border="0")\s(alt=").*?" 시도했지만 그것은 '국경'태그 여기

을 통해 강조 내가 사용하는 추출하기 위해 노력하고있어 텍스트의 난 그냥 텍스트를 추출하기 위해 노력하고

<img src="http://www.ebgames.com.au/0141/169/5.png"alt="Far Cry 3" title=" Far Cry 3 " class="photo"/>   </a> 

정규식 alt 태그의 따옴표 사이. 가능한 경우 제목 추출은 더 나을 것입니다. 도와주세요, 당신이

답변

1

이 정규식을 시도 감사 :

border=\"0\" alt=\"(.*?)\" 

데모 : 당신은 또한 긍정적 봐 미리 구현할 수 https://regex101.com/r/1kbiBv/1/

, 만 잡을 봐 숨김 긍정적 인 어떤 따옴표 사이 :

(?<=border=\"0\" alt=\").*?(?=\") 

데모 : https://regex101.com/r/1kbiBv/2/

+0

도움 주셔서 감사합니다. 이것은 간단하고 완벽하게 작동했습니다! – Kevin

0

BeautifulSoup와 HTML 요소와 속성을 추출하는 더 좋은 방법이있다 :

from bs4 import BeautifulSoup 
div_test='<img src="http://rcdn-1.fishpond.com.au/0141/169/297/319967448/5.jpeg" border="0" alt="The Durrells: Series 2" title=" The Durrells: Series 2 " class="photo"/> ' 
soup = BeautifulSoup(div_test, "lxml") 
result = soup.find("img").get('alt') 
result 

출력 :

'The Durrells: Series 2' 
+0

도움 주셔서 감사합니다! – Kevin

0

당신은 현재의 입력에서 태그를 추출하기 위해 lambda를 사용할 수 있습니다.

당신은이 코드를 시도 할 수 있습니다

:

import re 

a = '''<img src="http://rcdn-1.fishpond.com.au/0141/169/297/319967448/5.jpeg" border="0" alt="The Durrells: Series 2" title=" The Durrells: Series 2 " class="photo"/>   </a> 
''' 

find_tag = lambda x: r'{0}="(.*?)"'.format(x) 
# Same as doing: 
# regex = re.compile(find_tag('border="0" alt')) 
regex = re.compile(find_tag("alt")) 
text = re.findall(regex, a) 
print(text) 

출력 : 또한

['The Durrells: Series 2'] 

, 예를 들어,뿐만 아니라 다른 태그와 함께 작동합니다 코드 :

regex = re.compile(find_tag("src")) 
# Same as doing: 
# regex = re.compile(find_tag('<img src')) 
text = re.findall(regex, a) 
print(text) 

출력 :

['http://rcdn-1.fishpond.com.au/0141/169/297/319967448/5.jpeg'] 
0

간단한 정규 표현식을 사용하면 re.search으로 생각합니다.

import re 
s = '<img src="himg src="http://www.ebgames.com.au/0141/169/5.png" border="0" alt="Far Cry 3" title=" Far Cry 3 " class="photo"/>   </a>' 
pat = 'alt="([^"]*)".* title="([^"]*)".*"' 
a = re.search(pat, s) 
print(a[1]) # content in the alt tag : "Far Cry 3" 
print(a[2]) # content in the alt title : "Far Cry 3" 
0

이 코드는 'alt=".*?"' 패턴을 사용하여 필요한 것을 찾습니다.

import re 

w ='<img src="http://rcdn-1.fishpond.com.au/0141/169/297/319967448/5.jpeg" border="0" alt="The 
Durrells: Series 2" title=" The Durrells: Series 2 " class="photo"/> </a>' 

pattern = 'alt=".*?"' 
m = re.findall(pattern, w) 
print(m) 
+1

도움 주셔서 감사합니다! – Kevin