簡體   English   中英

Python正則表達式檢查字符串是否包含單詞

[英]Python regex check if string contains any of words

我想搜索一個字符串,看看它是否包含以下任何單詞: 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

您可以使用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"
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"

您可以使用findall查找所有匹配的單詞:

import re

s= 'Hello Ltd test AB ';

find_result = re.findall(r'AB|AG|AS|Ltd|KB|University', s)

if not find_result:
    print('No words found')    
else:
    print('Words found are:', find_result)

# The result for given example s is
# Words found are: ['Ltd', 'AB']

如果找不到任何單詞,則re.findall返回空列表。 另外最好不要使用str作為veritable的名稱,因為它會以相同的名稱覆蓋python中的內置函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM