如何从较大的字符串中检测具有特定模式的字符串?

How to detect a string with specific pattern from a larger string?

我有一个很长的字符串,我想从中检测并替换为其他一些文本。假设我的文字是'my first name is @[[Rameez]] and second name is @[[Rami]]'。我想检测 @[[Rameez]] 并用 Rameez 动态替换所有类似的字符串。

您可以创建一个正则表达式模式,然后使用它来匹配、查找和替换给定的字符串。示例如下:

string input = "This is   text with   far  too   much   " + 
                     "whitespace.";
      string pattern = "\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

它是 C# 代码,但您实际上可以将其应用于任何语言。在你的情况下,你可以用 string pattern = "@[[Rameez]]"; 之类的东西替换模式,然后使用不同的替换:string replacement = "Rameez"; 我希望这是有道理的。

你可以简单地做:

preg_replace('/@\[\[(\w+)\]\]/', "", $string);

[] 需要转义,因为它们在正则表达式中具有特殊含义。
这将用 whatever

替换任何字符串 @[[whatever]]

具体版本

// Find Rameez specifically
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?'; 

echo preg_replace($re, '', '**RAMEEZ** (specific)<br/>' . PHP_EOL);

普通版

正则表达式

@\[\[(?<name>.+?)\]\]

描述

(?<name> .. ) 在这里代表一个命名的捕获组。有关详细信息,请参阅 this answer

示例代码

// Find any name enclosed by @[[ and ]].
$re = '/@\[\[(?<name>Rameez)\]\]/i'; // Use i flag if you to want a case insensitive search
$str = 'my first name is @[[Rameez]] and second name is @[[Rami]].\nDid I forget to mention that my name is @[[rameez]]?'; 

echo preg_replace($re, '', '**RAMEEZ** (generic)<br/>' . PHP_EOL);

DEMO