views:

71

answers:

3

Hey all, i want to use a regular expression to match a word with one specified character randomly placed within it. I also want to keep that 'base' word's characters in their original order.

For example, with the 'base' word of test and the specified character of 'y', i want the regular expression to match all the following, and ONLY the following: ytest, tyest, teyst, tesyt, testy

Incase it matters, im working in javascript and using the dojo toolkit.

Thanks!

A: 

I think you can't do this with a single regular expression unless you're spelling it out explicitly - but \b(ytest|tyest|teyst|tesyt|testy)\b is probably not what you had in mind.

The next best regex-based solution would be to first match

\b(y)?t(y)?e(y)?s(y)?t(y)?\b

and then assert programmatically that only one of the five capturing groups actually matched something.

In the end, you're probably better off with a non-regex solution. Although I'd be glad to be proven wrong.

Tim Pietzcker
+3  A: 

Does it have to be Regex? If not will this do?

function matches(testWord, baseWord)
{
    for (var i =0; i < testWord.length; i++)
    {
    if(testWord.substr(0,i) + testWord.substr(i+1,testWord.length- i) == baseWord)
        return true;
}

return false;
}
Martin Smith
+1, I think regexes are the wrong tool for this.
Tim Pietzcker
How silly of me... i was fixed on using regex's to solve the problem.
Dfowj
A: 

In this one you can use a character class, like any number(/d) or some range of letters ([xyz]), if you pass the function a regexp for the third argument.

function matchPlus(string, base, plus){
    string= string.split(plus);
    return string.length== 2 && string.join('')== base;
}




//test case
var tA= 'ytest,tyest,teyst,test,ytesty,testyy,tesyt,testy'.split(','), L= 8;
while(L){
    tem= tA[--L];
    tA[L]= tem+'= '+!!matchPlus(tem,'test','y');
}

alert(testA.join('\n'))

/*  returned value: (String)
ytest= true
tyest= true
teyst= true
test= false
ytesty= false
testyy= false
tesyt= true
testy= true
*/
kennebec