我要判断字符串是以搜索的字符串开头、以搜索的字符串结尾,还是包含以以下内容开头的搜索的字符串:
-
一个或多个字母字符和空格
-
一个或多个字母字符加上一个点
然后是S、连字符或空格和字母数字字符.
如果搜索的关键字是Hansen:
- 这些都是应该匹配的案件.
const shouldMatchCases = [
"Hansen",
"Studio Hansen"
"Hansen-studio",
"Hansen studio",
"N.Hansen studio",
"N.Hansen-studio",
"N Hansens studio",
"N Hansen studio",
];
- 这些都是不应该匹配的情况.
const shouldNotMatchCases = [
"Hansenssutdio",
"Hansenstest",
"Hansenxxx",
"NormanHansen",
".Hansen-studio",
"Hansen-"
];
我试过这个正则表达式,但它不能匹配Hansen
和Studio Hansen
,也不能匹配.Hansen-studio
.
const regex = new RegExp(`(?:\\b|^)(?:[A-Za-z]+\\.)?(${etternavn})s?(-|\\s)[A-Za-z0-9]+`)
function matchesPattern(str, keyword) {
const regex = new RegExp(`(?:\\b|^)(?:[A-Za-z0-9]+\\.)?(${keyword})s?(-|\\s)[A-Za-z0-9]+`)
return regex.test(str);
}
// Test cases that should match
const shouldMatchCases = [
"Hansen",
"Test Hansen",
"Hansen-studio",
"Hansen studio",
"N.Hansen studio",
"N.Hansen-studio",
"N Hansens studio",
"N Hansen studio",
];
// Test cases that should not match
const shouldNotMatchCases = [
"Hansenssutdio",
"Hansenstest",
"Hansenxxx",
"NormanHansen",
".Hansen-studio",
"Hansen-"
];
// Test with dynamic keyword
const keyword = "Hansen";
console.log(`Testing with keyword: '${keyword}' for expected matches:`);
shouldMatchCases.forEach(str => {
console.log(`${str}: ${matchesPattern(str, keyword)}`);
});
console.log(`\nTesting with keyword: '${keyword}' for expected non-matches:`);
shouldNotMatchCases.forEach(str => {
console.log(`${str}: ${matchesPattern(str, keyword)}`);
});