我有这个功能来匹配通配符字符串:
stringMatchesWildcardPattern = function(string, wildcardPattern) {
var matches = null;
// Make string "event1" match wildcard pattern "event1.*"
if(wildcardPattern.endsWith('.*')) {
wildcardPattern = wildcardPattern.replaceLast('.*', '*');
}
// Build the pattern
var regularExpressionPattern = wildcardPattern.split('*').join('.*');
regularExpressionPattern = "^" + regularExpressionPattern + "$"
// Create the expression
var regularExpression = new RegExp(regularExpressionPattern);
// Evaluate the expression
matches = regularExpression.test(string);
return matches;
};
不幸的是,它不健壮,并且应该通过这个输入失败:
stringMatchesWildcardPattern('one.two.*', 'one.*.three.*');
我很难绕过如何解决这个问题。一直在看这个问题太久了。关于如何更新我的函数以解决此输入的任何想法?
以下是我的测试用例:
Assert.true(stringMatchesWildcardPattern('event1', 'event1.*'), '"event1" matches wildcard pattern, "event1.*"');
Assert.true(stringMatchesWildcardPattern('event1.secondLevelEvent1', 'event1.*'), '"event1.secondLevelEvent1" matches wildcard pattern, "event1.*"');
Assert.true(stringMatchesWildcardPattern('event1.secondLevelEvent1.thirdLevelEvent1', 'event1.secondLevelEvent1.*'), '"event1.secondLevelEvent1.thirdLevelEvent1" matches wildcard pattern, "event1.secondLevelEvent1.*"');
Assert.true(stringMatchesWildcardPattern('event1.secondLevelEvent1.thirdLevelEvent1', 'event1.*'), '"event1.secondLevelEvent1.thirdLevelEvent1" matches wildcard pattern, "event1.*"');
Assert.true(stringMatchesWildcardPattern('event123', 'event*'), '"event123" matches wildcard pattern, "event*"');
Assert.true(stringMatchesWildcardPattern('event123event', 'event*event'), '"event123event" matches wildcard pattern, "event*event"');
Assert.true(stringMatchesWildcardPattern('123event123event123', '*event*event*'), '"123event123event123" matches wildcard pattern, "*event*event*"');
Assert.true(stringMatchesWildcardPattern('keyboard.key.*.up', 'keyboard.key.*.up.*'), '"keyboard.key.*.up" matches wildcard pattern, "keyboard.key.*.up.*"');
Assert.false(stringMatchesWildcardPattern('event', 'event1.*'), '"event" does not match wildcard pattern "event1.*"');
Assert.false(stringMatchesWildcardPattern('event', 'event1.*.*'), '"event" does not match wildcard pattern "event1.*.*"');
Assert.false(stringMatchesWildcardPattern('123event', 'event'), '"123event" does not match wildcard pattern, "event"');
Assert.false(stringMatchesWildcardPattern('123event123', 'event*'), '"123event123" does not match wildcard pattern, "event*"');
Assert.false(stringMatchesWildcardPattern('123event123event123', 'event*event*'), '"123event123event123" does not match wildcard pattern, "event*event*"');
Assert.true(stringMatchesWildcardPattern('one.two.*', 'one.*.three.*'), '"one.two.*" match wildcard pattern, "one.*.three.*"');