How to find the text from in between parentheses from a word in comment? eg. I want to find the text in codeword(findthistext)

I commented earlier, but found some bugs, here's my PHP coding attempt I created:


I have no idea how to code in python, but that's an interesting problem... Searching for "codeword(" is the easy part, but what you could then do to find the "end" is something like this (using php as an example):

//Find the codeword
$startP = strpos($comment, "codeword(") + 9;

//Trim all prior text of the comment before the "("
$findthis = substr($comment, $startP);

//Find the end of the parentheses
$endP = strpos($findthis, ")");

//Get text within parentheses    
$tempfindthis = substr($findthis,0,$endP);

//BUT.. if there's "(" inside...
$newStartP = strpos($tempfindthis, "(");
while ( $newStartP !== false ) {

    //..ignore the original ")", and find the next one
    $newEndP = strpos($findthis, ")", $endP+1);

    //If there IS another ")" found, continue checking for "("
    if ( $newEndP !== false ) {
        $endP = $newEndP;
        $tempfindthis = substr($findthis,$newStartP);
        $newStartP = strpos($tempfindthis, "(");
    //Otherwise, use the last ")"
    } else {
        $tempfindthis = "";
        $newStartP = false;
    }
}

//Trim all text after the last relevant ")"
$findthis = substr($findthis,0,$endP);

if $comment is "some text codeword(hello world) with some more text", $findthistext will be "hello world".

if $comment is "some text codeword(hello world) with some more text codeword(hello again) and some more", $findthistext will be "hello world".

if $comment is "some text codeword(bad ( in the middle) with some more text", $findthistext will be "bad ( in the middle".

if $comment is "did you know that codeword(jeff likes (stuff), the illegal (stuff (which tastes good) stuff) in his cereal) and it's so good.", $findthistext will be "jeff likes (stuff), the illegal (stuff (which tastes good) stuff) in his cereal".

/r/redditdev Thread