2011-01-14 17 views
2

私はPythonには新しく、一般的に開発しています。私がしようとしていることの例を挙げましょう。正規表現を使ってPythonでデータを見つける

私はテキスト名=「ユーザ名」タイプ=「隠された」値=「何とか」と私は唯一の「何とか」私はそれについて移動し始める方法

を引きたいを見つけたいですか?多分このような

+2

あなたの例では、ほぼ見えます[正規表現でHTMLを解析する](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)、これはお勧めできません。 – aaronstacy

答えて

3

string = 'name="username" type="hidden" value="blah"' 
#get the text between the quotes that is lead by an equal sign and a non whitespace character. 
regex = re.compile('\S="([^"]+)"') 
print regex.findall(string) 

これらはPythonで正規表現のための素晴らしいリソースですマッチの部分。

#!/usr/bin/env python 

s = """ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do 
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim 
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea 
commodo consequat. 
name="username" type="hidden" value="blah" 
Duis aute irure dolor in reprehenderit in voluptate velit 
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat 
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 
""" 

import re 

pattern = re.compile(r'name="username"\stype="hidden"\svalue="([^"]*)"') 
for match in pattern.finditer(s): 
    print match.group(1) 
    # => blah 
+0

リテラルで+1の場合 – Falmarri

+0

私はblahの価値を知らないとどうなりますか?それは私がつかみたいもので、変更することができます – mahle

+0

'[^"] * ';で' blah'を置き換え、私の投稿を更新しました。 – miku

0

あなたが辞書にすべての値を取得したい場合は、この機能を使用することができます。

import re 

def get_pair_map(s): 
    map = {} 
    pair_re = re.compile('(\w+)="(\w+)"') 
    map.update(pair_re.findall(s)) 
    return map 
0

他はPythonの標準ライブラリにreモジュールを使用しての優れた例を与えているが、 Pythonの汎用文字列処理の使用を検討することもできます。それはimportのことを避け、通常はもっと「Pythonic」とみなされます。

例ライン:あなたがしようとしているよう

名= "ユーザ名" タイプ= "隠された" 値= "何とか"

# given a file of the example line 
for line in open('my_file.txt'): 
    # split on the spaces in the line 
    for item in line.split(): 
      # check if this is the 'value' attribute you need 
      if 'value' in item: 
       print item.split('"')[1] 
関連する問題