DEV Community

Cover image for RegEx match all words with a prefix
Adam K Dean
Adam K Dean

Posted on

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

Top comments (0)