Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

regex javascript - match multiple search terms ignoring their order

I would like to find all the matches of given strings (divided by spaces) in a string. (The way for example, iTunes search box works).

That, for example, both "ab de" and "de ab" will return true on "abcde" (also "bc e a" or any order should return true)

If I replace the white space with a wild card, "ab*de" would return true on "abcde", but not "de*ab". [I use * and not Regex syntax just for this explanation]

I could not find any pure Regex solution for that. The only solution I could think of is spliting the search term and run multiple Regex.

Is it possible to find a pure Regex expression that will cover all these options ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Returns true when all parts (divided by , or ' ') of a searchString occur in text. Otherwise false is returned.

filter(text, searchString) {
    const regexStr = '(?=.*' + searchString.split(/,|s/).join(')(?=.*') + ')';
    const searchRegEx = new RegExp(regexStr, 'gi');
    return text.match(searchRegEx) !== null;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...