Вы можете заменить пробелы на \s+
в term
и использовать сопоставление без учета регистра, передав флаг re.I
:
import re
ss = ["Hello there how are you?", "Hello there how are you?", "Hello There How are you?"]
term = "there how"
rx = re.compile(r"(?<!\S){}(?!\S)".format(term.replace(r" ", r"\s+")), re.I)
for s in ss:
m = re.search(rx, s)
if m:
print(m.group())
Вывод:
there how
there how
There How
См. Python demo
ПРИМЕЧАНИЕ : если term
может содержать специальные метасимволы регулярных выражений, вам необходимо re.escape
term
, но сделайте это перед заменойпробелы с \s+
.Поскольку пробелы экранируются с помощью re.escape
, вам необходимо .replace(r'\ ', r'\s+')
:
rx = re.compile(r"(?<!\S){}(?!\S)".format(re.escape(term).replace(r"\ ", r"\s+")), re.I)
Решение JavaScript:
var ss = ["Hello there how are you?", "Hello there how are you?", "Hello There How are you?"];
var term = "there how";
var rx = new RegExp("(?<!\\S)" + term.replace(/ /g, "\\s+") + "(?!\\S)", "i");
for (var i=0; i<ss.length; i++) {
var m = ss[i].match(rx) || "";
console.log(m[0]);
}