2010-12-16 11 views
1

から引っ張る日付私は、Webページからのテキストの通常の文字列を引っ張ってはPythonを使用しているよ - ソースコードは次のように実行します:初心者Pythonの正規表現の質問:Webページ

<br /><strong>Date: 06/12/2010</strong> <br /> 

それは常に

を開始します
<strong>Date: 

&は、私はすでに、WebページのテキストとちょうどWAを掻き取ってきた

</strong> 

を終了します日付と同様に構造化された情報を引き出すこと。どのようにこれを行うための任意の提案? (申し訳ありませんが、このような初心者の質問です!)あなたは正規表現を使用することができます

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – katrielalex

答えて

1
import re 

text = "<br /><strong>Date: 06/12/2010</strong> <br />" 
m = re.search("<strong>(Date:.*?)</strong>", text) 
print m.group(1) 

出力

Date: 06/12/2010 
+0

さらにもう1人は貪欲によって噛まれる...これはあなたは最初の 'データ:'から最後の ''までのすべてのものに及ぶ本当に大きなグループです。 – delnan

+0

修正: '。*'を '。*? 'に置き換えてください。 – nmichaels

+0

@delnan True。私は訂正した! – Rod

3

import re 
pattern = re.compile(r'<strong>Date:(?P<date>.*?)</strong>') # re.MULTILINE? 
# Then use it with 
pattern.findall(text) # Returns all matches 
# or 
match = pattern.search(text) # grabs the first match 
match.groupdict() # gives a dictionary with key 'date' 
# or 
match.groups()[0] # gives you just the text of the match. 

またはbeautiful soupで事を解析しようとします。

Thisは、Python正規表現をテストするのに適しています。

+0

誰かが '?P 。*?'魔法について説明してもらえますか? – Pete

+1

これはグループに名前(日付)を与えます。厳密には必要ではありません。 'P 'を除外することができますが、 'match.groupdict()'は動作しません。 http://docs.python.org/library/re.htmlで '?P <'を探します – nmichaels

関連する問題