Take the 2-minute tour ×

I'm wondering if it's possible to extract a number of variables from a predefined sentence with regex or similar.


If this was the pattern...

"How many * awards did * win in *?"

And someone typed...

"How many gold awards did johnny win in 2008?"

How can I somehow return...


I'd also like to return the fact that it matches the pattern before retrieving the variables as there will be many different patterns. Note: It will also be possible for someone to type multiple words in place of a * e.g. johnny english instead of just johnny


share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Building on Derek's answer and SimpleCoder's comment, here would be the full function:

// This function escapes a regex string
// http://simonwillison.net/2006/jan/20/escape/
function escapeRegex(text) {

function match(pattern, text) {
    var regex = '^' + escapeRegex(pattern).replace(/\\\*/g, '(.+)') + '$';
    var query = text.match(new RegExp(regex, 'i'));
    if (!query)
        return false;

    query.shift(); // remove first element
    return query;

match("How many * awards did * win in *?", "How many gold awards did johnny win in 2008?");
share|improve this answer
Genius! Thanks Derek and Casey. These functions work a treat. I am also considering porting this to PHP too. Are there similar regex features in PHP? Thanks –  Mulhoon Jun 28 '12 at 10:50
add comment
var text = "How many gold awards did johnny win in 2008?";
var query = text.match(/^How many ([^\s]+) awards did ([^\s]+) win in ([^\s]+)\?$/i);
query.splice(0,1); //remove the first item since you will not need it
query[0] //gold
query[1] //johny
query[2] //2008

For more information, see MDN - match.


Seems like you want to match johny english in How many gold awards did johnny english win in 2008?.
This is a updated version of the regex:

/^How many (.+) awards did (.+) win in (.+)\?$/i
share|improve this answer
To add to this, you could dynamically build the regex by replacing the * character with ([^\s]+) given a pattern string. –  Chris Laplante Jun 27 '12 at 18:46
@SimpleCoder - And change every ? into \? –  Derek 朕會功夫 Jun 27 '12 at 18:47
Yep, and other special characters too :) –  Chris Laplante Jun 27 '12 at 18:48
The match function docs. –  katspaugh Jun 27 '12 at 18:49
For the sake of slight simplification, ([^\s]+) is the same as (\S+). –  Wiseguy Jun 27 '12 at 18:49
add comment

Your Answer


