View Single Post
Old 01-31-2013, 09:18 PM   PM User | #11
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,575
Thanks: 62
Thanked 4,062 Times in 4,031 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Here's my answer.

I'll let you figure out if you can combine the 4 regexp's into one.

Note that I stop on the first match, because some text patterns will match more than one of the regexps, but the regexps are purposely ordered by most desirable match.

The hack to get rid of a leading period is just that: a hack. But it works.

Code:
<script type="text/javascript">
function findSentenceByWord( text, word )
{
    var re1 = new RegExp( "[A-Z\\.][^A-Z\\.]+?" + word + "[^\\.\\?\\!]*[\\.\\?\\!]", "" );
    var re2 = new RegExp( "^[\\s\\S]*?" + word + "[^\\.\\?\\!]*[\\.\\?\\!]", "" );
    var re3 = new RegExp( "[A-Z\\.][^A-Z\\.]+?" + word + "[\\s\\S]*$", "" );
    var re4 = new RegExp( "^[\\s\\S]*?" + word + "[\\s\\S]*$", "" );
    var res = [ re1, re2, re3, re4 ];
    for ( var r = 0; r < res.length; ++r )
    {
        var re = res[r];
        if ( re.test( text ) )
        {
            document.write("Match on regexp " + (r+1) + "<br/>");
            var m = text.match(re)[0];
            if ( m.charAt(0) == "." ) { m = m.substring(1); }
            document.write( m + "<br/>");
            return;
        }
    }
}

function demo( text, word )
{
    document.write( "<hr/>Testing <i><b>" + text + "</b></i> for word " + word + "<br/>" );
    findSentenceByWord( text, word );
}    

demo( "The dog jumped over the moon. He was happy to see me. I left in a hurry", "happy" );
demo( "was happy to see me. I left in a hurry", "happy" );
demo( "The dog jumped over the moon. He was happy to see", "happy" );
demo( "aardvarks whistle. happy dogs bark", "happy" );
demo( "happy happy happy! and even more happy?", "happy" );
demo( "all the happy dogs", "happy" );</script>
I dump out which regexp matched so that you can see that indeed all 4 are needed, depending on the input.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is online now   Reply With Quote