Python正则表达式检查字符串是否包含单词

Alo*_*ius 1 python regex

我想搜索一个字符串,看看它是否包含以下任何单词: AB|AG|AS|Ltd|KB|University

我有这个工作在JavaScript中:

var str = 'Hello test AB';
var forbiddenwords= new RegExp("AB|AG|AS|Ltd|KB|University", "g");

var matchForbidden = str.match(forbiddenwords);

if (matchForbidden !== null) {
   console.log("Contains the word");
} else {
   console.log("Does not contain the word");
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能使上述工作在python中?

Sha*_*ath 5

您可以使用 re 模块。请尝试以下代码:

import re
exp = re.compile('AB|AG|AS|Ltd|KB|University')
search_str = "Hello test AB"
if re.search(exp, search_str):
  print "Contains the word"
else:
  print "Does not contain the word"
Run Code Online (Sandbox Code Playgroud)


use*_*459 5

import re
strg = "Hello test AB"
#str is reserved in python, so it's better to change the variable name

forbiddenwords = re.compile('AB|AG|AS|Ltd|KB|University') 
#this is the equivalent of new RegExp('AB|AG|AS|Ltd|KB|University'), 
#returns a RegexObject object

if forbiddenwords.search(strg): print 'Contains the word'
#search returns a list of results; if the list is not empty 
#(and therefore evaluates to true), then the string contains some of the words

else: print 'Does not contain the word'
#if the list is empty (evaluates to false), string doesn't contain any of the words
Run Code Online (Sandbox Code Playgroud)

  • 如果您可以在回答中添加更多解释,以帮助提出问题的人理解为什么这会对他有所帮助,那将是很好的。 (3认同)

ben*_*les 3

str="Hello test AB"
to_match=["AB","AG","AS","Ltd","KB","University"]
for each_to_match in to_match:
    if each_to_match in str:
        print "Contains"
        break
else:
    print "doesnt contain"
Run Code Online (Sandbox Code Playgroud)