0

Python正規表現キーワードを含む文字列がありますが、キーワードが存在せず、特定の順序ではない場合があります。正規表現について助けが必要です。

キーワードは次のとおりです。

Up-to-date
date added
date trained

これらは、他の多くのキーワードの中から見つける必要があるキーワードであり、存在しない可能性があり、任意の順序になります.

刺傷はどのように見えるか

<div>
<h2 class='someClass'>text</h2>

 blah blah blah Up-to-date blah date added blah

</div>

私が試したこと:

regex = re.compile('</h2>.*(Up\-to\-date|date\sadded|date\strained)*.*</div>') 

regex = re.compile('</h2>.*(Up\-to\-date?)|(date\sadded?)|(date\strained?).*</div>')

re.findall(regex,string) 

私が探している結果は次のとおりです。

If all exists
['Up-to-date','date added','date trained']

If some exists
['Up-to-date','','date trained']
4

2 に答える 2

0

このコードはあなたが望むことをします、しかしそれはにおいがします:

import re

def check(the_str):
    output_list = []
    u2d = re.compile('</h2>.*Up\-to\-date*.*</div>') 
    da = re.compile('</h2>.*date\sadded*.*</div>')
    dt = re.compile('</h2>.*date\strained*.*</div>')
    if re.match(u2d, the_str):
        output_list.append("Up-to-date")
    if re.match(da, the_str):
        output_list.append("date added")
    if re.match(dt, the_str):
        output_list.append("date trained")

    return output_list

the_str = "</h2>My super cool string with the date added and then some more text</div>"
print check(the_str)
the_str2 = "</h2>My super cool string date added with the date trained and then some more text</div>"
print check(the_str2)
the_str3 = "</h2>My super cool string date added with the date trained and then Up-to-date some more text</div>"
print check(the_str3)
于 2012-05-11T23:46:50.990 に答える
0

正規表現である必要がありますか?そうでない場合は、次を使用できますfind

In [12]: sentence = 'hello world cat dog'

In [13]: words = ['cat', 'bear', 'dog']

In [15]: [w*(sentence.find(w)>=0) for w in words]
Out[15]: ['cat', '', 'dog']
于 2012-05-11T23:41:57.227 に答える