我想搜索一个字符串并查看它是否包含以下任何单词: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");
}
我怎样才能在Python中实现上述工作?
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)