質問概要
文章中に含まれるURLを、正規表現で全て取得したい
質問概要
文章中に含まれるURLを、正規表現で全て取得したいと考えています。
その上で、以下のコードをサンプルとして書いてみました。
lang
1#!/usr/bin/env python 2# -*- coding: utf8 -*- 3 4import re 5 6pattern = u"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" 7text = "aaaaahttp://www.google.com/\naaaa" 8matchOB = re.search( pattern , text) 9 10print matchOB.group(0)
たったこれだけなのですが、以下のようなエラーが出ます。
pattern = r"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"
としてもだめでした。(u"〜"→r"〜")
lang
1Traceback (most recent call last): 2 File "test.py", line 11, in <module> 3 matchOB = re.search( unicode(pattern, 'utf-8') , text) 4TypeError: decoding Unicode is not supported
試しに、
lang
1#!/usr/bin/env python 2# -*- coding: utf8 -*- 3 4import re 5 6 7pattern = "a" 8 9text = "aaaaahttp://www.google.com/\naaaa" 10matchOB = re.search( pattern , text) 11 12print matchOB.group(0)
とすると、
lang
1$ python test.py 2a
のように、しっかり返ってきました。
これは何が原因なのでしょうか?
ご存じの方がいらっしゃいましたら、ご教示願います。
環境
Python 2.7.10
MacOS X 10.10.5(Yosemite)
修正依頼からの修正
コード
lang
1#!/usr/bin/env python 2# -*- coding: utf8 -*- 3 4import re 5 6text = u'hogehoge http://www.example.com/ mugemuge' 7 8 9# URLを抜き出し 10urls = re.search(u'http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?', text) 11 12for i in urls: 13 print i
エラー
Traceback (most recent call last): File "test.py", line 10, in <module> urls = re.search(u'http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?', text) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search return _compile(pattern, flags).search(string) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile raise error, v # invalid expression sre_constants.error: bad character range
回答1件
あなたの回答
tips
プレビュー