Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex check if string contains any of words

Tags:

python

regex

I want to search a string and see if it contains any of the following words: AB|AG|AS|Ltd|KB|University

I have this working in 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");
}

How could I make the above work in python?

like image 396
Alosyius Avatar asked Dec 07 '22 01:12

Alosyius


1 Answers

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
like image 62
user3725459 Avatar answered Dec 08 '22 13:12

user3725459