Python,如果字符串中的子字符串在子字符串的开头不包含任何[a-zA-Z0-9_]

时间:2014-08-19 11:44:33

标签: string python-2.7

我有一个名为programs_cache的字符串,其中包含多个程序名称和描述:

abcde - A Better CD Encoder
abcm2ps - Translates ABC music description files to PostScript (or SVG)
abcmidi - converter from ABC to MIDI format and back
abcmidi-yaps - yet another ABC to PostScript converter
cd-discid - CDDB DiscID utility
cl-launch - uniform frontend to running Common Lisp code from the shell
cppcheck - tool for static C/C++ code analysis
grabc - simple program to determine the color string in hex by clicking on a pixel
gregorio - command-line tool to typeset Gregorian chant

我希望有一个IF语句在搜索program_name字符串中的programs_cache时返回True,但如果搜索没有提供,则不应返回True全名。

例如:搜索abc应返回False,但搜索grabc应返回True。

我在尝试这个: if program_name+" " in programs_cache and not re.search([w]+program_name+" ",programs_cache):

但我收到错误NameError: global name 'w' is not defined

使用W的想法是为了匹配program_name之前的任何单个字符。

如基本模式中所述: w匹配“单词”字符:字母或数字或下划线[a-zA-Z0-9_]。 它只匹配单个字符而不是整个单词。

我知道我使用了错误的函数re.search()和基本模式,但在这种情况下我还没弄清楚如何正确使用它。

1 个答案:

答案 0 :(得分:1)

# do this once during program start
program_names = set(line.partition(' - ')[0] for line in programs_cache)

# do this for each lookup
if program_name in program_names:
    print "got it"
else:
    print "don't got it"