2010-02-24 6 views
2

에 HTML 링크를 대체 :정규식은 일반 텍스트 URL을 나는 HTML로 링크를 교체해야

<a href="http://example.com"></a> 

그냥 일반 텍스트 URL 주소 :

http://example.com 

UPD를. 여기에 몇 가지 설명, 텍스트에서 html 태그를 스트립하지만 링크 위치를 보존해야합니다. 그것은 순수하게 내부 사용을위한 것입니다, 그래서 어떤 미친 edge-case 코드도 없을 것입니다. 이 경우 Python 언어가 사용되지만 관련성이 없습니다. 내가 말했듯이 더 복잡한 작업

+6

당신이 정규식을 사용하지 않는, HTML을 조작해야합니다. –

+0

인수로 들어가는 것은 그냥 위생 처리 이거나 다른 비트가있을 것이라고 확신 할 수 있습니까? – Layke

+0

너무 모호합니다. 어떤 언어, 환경? –

답변

1
>>> s="""blah <a href="http://example.com"></a> blah <a href="http://www.google.com">test</a>""" 
>>> import re 
>>> pat=re.compile("<a\s+href=\"(.*?)\">.*?</a>",re.M|re.DOTALL|re.I) 
>>> pat.findall(s) 
['http://example.com', 'http://www.google.com'] 
>>> pat.sub("\\1",s) 
'blah http://example.com blah http://www.google.com' 

는, 대신 정규식을 사용하는 BeautifulSoup로에게

+2

앵커 태그에 다른 속성이있는 경우 작동하지 않을 것입니다.이를 조정하려고하면, 귀하의 정규식은 신속하게 제어 할 수 없게됩니다. – Nicole

+0

간단하고 작동합니다. 감사합니다 –

0

를 사용하여, 당신은 minidom

+0

음, 어떻게 작동할까요? :) –

2

unlink를 사용을 시도 할 수 있습니다 전에 몇 가지 실수와 확인 및/또는이있는 경우 입력에 대한 어느 정도의 통제가 있다면, 당신은 완전성에서 약간의 타협을하고 Regex를 사용할 수 있습니다. 당신의 업데이트는 이러한 경우라고 때문에, 여기 당신을 위해 작동해야 정규식입니다 :

/<a\s(?:.(?!=href))*?href="([^"]*)"[^>]*?>(.*?)</a>/gi 
  • $ (1) : href를
  • $ 2 : 태그 내부의 모든.

이 지난 3 개 라인을 제외하고 아래의 모든 테스트 케이스를 처리합니다 :

Hello this is some text <a href="/test">This is a link</a> and this is some more text. 
<a href="/test">Just a link on this line.</a> 
There are <a href="/test">two links </a> on <a href="http://www.google.com">this line</a>! 
Now we need to test some <a href="http://www.google.com" class="test">other attributes.</a>. They can be <a class="test" href="http://www.google.com">before</a> or after. 
Or they can be <a rel="nofollow" href="http://www.google.com" class="myclass">both</a> 
Also we need to deal with <a href="/test" class="myclass" style=""><span class="something">Nested tags and empty attributes</span></a>. 
Make sure that we don't do anything with <a name="marker">anchors with no href</a> 
Make sure we skip other <address href="/test">tags that start with a even if they are closed with an a</a> 
Lastly try some other <a href="#">types</a> of <a href="">href</a> attributes. 

Also we need to skip <a malformed tags. </a>. But <a href="#">this</a> is where regex fails us. 
We will also fail if the user has used <a href='javascript:alert("the reason"))'>single quotes for some reason</a> 
Other invalid HTML such as <a href="/link1" href="/link2">links with two hrefs</a> will have problems for obvious reasons. 
+0

우수 답변, 감사합니다. –