3

我正在寻找一个函数/正则表达式,它可以找到给定的单词并重新运行下一个单词,例如:Giving the input "is"

并在这个字符串中搜索

"the force is strong with you but you are not a jedi yet" 

会回来 "strong"

搜索“你”将返回一个包含{"but","are"}.

我正在寻找一个最好用 PHP 或 C# 编写的代码示例。

4

4 回答 4

3

使用 C#:

var search = "you";
var str = "the force is strong with you but you are not a jedi yet";
var matches = Regex.Matches(str, search + @"\s(\w+)");

foreach (Match word in matches)
{
    Console.WriteLine(word.Groups[1].Value);
}

这假设您搜索的单词后面有一个空格。相同的正则表达式可以在 PHP 中工作(显然没有@and 分隔符)。

于 2013-05-15T14:02:16.787 回答
3

你可以试试

(?:\bis\b)\s*(\b\w*\b)

在此处输入图像描述

在此处输入图像描述

例子

PHP Code Example: 
<?php
$sourcestring="your source string";
preg_match_all('/(?:\bis\b)\s*(\b\w*\b)/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

$matches Array:
(
    [0] => Array
        (
            [0] => Is that
            [1] => is strong
            [2] => is that
        )

    [1] => Array
        (
            [0] => that
            [1] => strong
            [2] => that
        )

)
于 2013-05-15T14:10:16.787 回答
0

C# 示例:

var words = new List<string>();
string wordToSearch = "you";
string strTargetString = @"the force is strong with you but you are not a jedi youu yet";

string strRegex = string.Format(@"(\b{0}\b)\s+(\b.+?\b)", wordToSearch);
RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.CultureInvariant;
Regex myRegex = new Regex(strRegex, myRegexOptions);


foreach(Match myMatch in myRegex.Matches(strTargetString))
{
    string word = myMatch.Groups[2].Value;
    words.Add(word);
}
于 2013-05-15T14:13:43.093 回答
0

没有正则表达式的 php 函数:

$str = "the force is strong with you but you are not a jedi yet";
$res = getTheNextOne('you', $str);

echo '<pre>' . print_r($res,true) . '</pre>';
//Array
//(
//  [0] => but
//  [1] => are
//)

function getTheNextOne($needle, $str) {

    $res = array();

    $tmp = explode(' ', $str);
    $length = count($tmp);

    //$length-1 as there is no next word for the last one
    for($i=0; $i < $length-1; $i++) {
        if($tmp[$i] == $needle) {
            $res[] = $tmp[$i+1];
        }
    }

    $nbFound = count($res);

    if($nbFound == 0) {
        return null;
    } elseif ($nbFound == 1) {
        return $res[0];
    } else {
        return $res;
    }
}
于 2013-05-15T14:28:16.397 回答