在我的解决方案中,我在三个不同的捕获组(分别是第二个、第三个和第四个;第一个是捕获的空间)中捕获 X、Y 和 Z。
使用调用回调函数(名为 CallBack),我在每个组中查看哪一个具有值并替换为正确的文本(“abc”、“def”或“ghi”)。
这里的关键元素是回调函数。有时,要进行非常复杂的替换(例如您问题中的条件替换),您绝对需要使用回调函数。
这里的另一个关键概念是,如果捕获组无法匹配任何内容,则它们将返回一个空字符串。
using System;
using System.Text.RegularExpressions;
string input = "same X same Y same Z";
var myRegex = new Regex("same(\\s*)(?:(X)|(Y)|(Z))", RegexOptions.IgnoreCase);
string output = myRegex.Replace(input, Callback);
Console.WriteLine(output);
static string Callback(Match match) {
string toReturn = "";
if (match.Groups[2].Value != "") {
toReturn = "abc";
} else if (match.Groups[3].Value != "") {
toReturn = "def";
} else if (match.Groups[4].Value != "") {
toReturn = "ghi";
}
return toReturn + match.Groups[1].Value + match.Groups[2].Value +
match.Groups[3].Value + match.Groups[4].Value;
}
你可以在这里测试它:http://csharppad.com/gist/5c921d27cefad32a6d353a26a6906405
我已经很多年没有接触过 C#了,我花了很长时间才写出那个简单的代码示例,所以不要指望我会提供太多进一步的帮助。
成功
编辑:我将用 PHP 编写算法,因为这是我现在使用最多的语言。
$test = new Test();
echo $test->callbackregex(
'/same(\s*)(?:(X)|(Y)|(Z))/i',
array(
2 => array('abc', '$1' ,'$2'),
3 => array('def', '$1' ,'$3'),
4 => array('ghi', '$1' ,'$4')
),
"same X same Y same Z"
);
class Test
{
private $replacement = array();
public function callbackregex($regex, array $replacement, $input)
{
$this->replacement = $replacement;
return preg_replace_callback(
$regex,
array($this, "callback"),
$input
);
}
private function callback($matches)
{
$toReturn = "";
$total = count($matches);
//I skip 0 because it is the overall match of the regex
for($index = 1; $index < $total; $index++) {
if (!empty($matches[$index]) and isset($this->replacement[$index])) {
$replacementArray = $this->replacement[$index];
if (is_string($replacementArray)) {
$replacementArray = array($replacementArray);
}
foreach ($replacementArray as $replacement) {
if (preg_match('/^\$\d+$/', $replacement)) {
$i = (int) str_replace('$', '', $replacement);
if (isset($matches[$i])) {
$toReturn .= $matches[$i];
}
} else {
$toReturn .= $replacement;
}
}
}
}
return $toReturn;
}
}
测试:http://sandbox.onlinephpfunctions.com/code/85a5547c7194b36c763a0f8dc7672e5785ec2044