RegEx match all words with a prefix

adamkdean

Adam K Dean

Posted on July 17, 2014

RegEx match all words with a prefix

Here is a snippet to match all words that begin with a specified prefix.

/\bprefix\S+/g
Enter fullscreen mode Exit fullscreen mode

JavaScript implementation:

"test tbl_test1 tbl_test2 test".match(/\btbl_\S+/g)
Enter fullscreen mode Exit fullscreen mode

Or

/\btbl_\S+/g.exec("test tbl_test1 tbl_test2 test")
Enter fullscreen mode Exit fullscreen mode

Which is the same as:

var regex = /\btbl_\S+/g;
    matches = [],
    match;

while (match = regex.exec(line)) {
    matches.push(match[0]);
}
Enter fullscreen mode Exit fullscreen mode

If you want a dynamic prefix, use RegExp:

var regex = new RegExp('\\b' + prefix + '\\S+', 'g'),
    matches = [],
    match;

while (match = regex.exec(line)) {
    matches.push(match[0]);
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
adamkdean
Adam K Dean

Posted on July 17, 2014

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related