How To Match A String That Contains Given Characters In A Given Order?
Solution 1:
A straightforward pattern would be simply: m.*r.*i.*e.*
. However, I assume that you do not only want to match files with the .js extension, and that the pattern matching should only match the filename and not its extenion. In this case, the simplified pattern would cause trouble if your extension contains any of those characters.
Food for thought: what about the following pattern?
m[a-z0-9\-_]*?r[a-z0-9\-_]*?i[a-z0-9\-_]*?e[a-z0-9\-_]*?\.[a-z]+
A brief explanation of what the pattern does:
- Ensures m, r, i and e to be in the right order
- Allows 0 or more characters (alphanumeric and underscore) to be in between each of them. The use of '?' denotes a lazy selection: the engine will try to match the least number of characters before moving on.
However, the pattern also assumes that you would only want to accept alphanumeric and underscore characters. You can add more symbols between the square brackets should you want to include other characters (but remember to escape the important ones).
To do the matching in JS, you can use:
var patt = /m[a-z0-9\-_]*?r[a-z0-9\-_]*?i[a-z0-9\-_]*?e[a-z0-9\-_]*?\.[a-z]+/gi;
if(fileName.match(patt)) {
// If there is a match
} else {
// If there is no match
}
[Edit] OP asked if it is possible to bold the highlighted characters. I suggested using the .replace()
function:
var patt = /m([a-z0-9\-_]*?)r([a-z0-9\-_]*?)i([a-z0-9\-_]*?)e([a-z0-9\-_]*\.[a-z]+)/gi;
var newFileName = fileName.replace(patt, "<strong>m</strong>$1<strong>r</strong>$2<strong>i</strong>$3<strong>e</strong>$4");
For the sake of completeness, here is a proof-of-concept fiddle ;)
Solution 2:
I think this is all you need:
m.*r.*i.*e
Post a Comment for "How To Match A String That Contains Given Characters In A Given Order?"