查找单词并返回下一个单词的正则表达式或函数

3
我正在寻找一个函数/正则表达式,可以查找给定的单词并返回下一个单词,例如: 给定输入 "is" 在该字符串中搜索:
"the force is strong with you but you are not a jedi yet" 

将会返回"strong"

搜索 "you" 将返回一个包含{"but","are"}的数组。

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

4个回答

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
        )

)

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中使用(显然不需要使用@,且要使用分隔符)。


我喜欢你的解决方案,但更喜欢Denomales的解决方案,因为它考虑了多个空格。 - Artur Kedzior

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;
    }
}

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接