Adam K Dean

RegEx match all words with a prefix

Published on 17 July 2014 at 15:47 by Adam

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

/\bprefix\S+/g

JavaScript implementation:

"test tbl_test1 tbl_test2 test".match(/\btbl_\S+/g)

Or

/\btbl_\S+/g.exec("test tbl_test1 tbl_test2 test")

Which is the same as:

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

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

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]);
}


This post was first published on 17 July 2014 at 15:47. It was filed under archive with tags javascript, regex.