将字符串中的正则表达式模式替换为依赖于匹配项的替换字符串

Replace a regex pattern in a string with a replacement string dependant on the match

本文关键字:替换 字符串 依赖于 模式 正则表达式      更新时间:2023-09-26

我有一个包含变量的特殊字符串。任何以"@"符号开头的单词都是此字符串中的变量。

示例 foostring

这是我的字符串,这是其中的@variable。 例如,@hello是 另一个变量

我想执行一个操作,用 %-变量-% 替换此类特殊字符串中的任何通用变量 @-variable-

所以上面的示例 foostring 字符串将变为这样(在此操作之后):

这是我的字符串,这是其中的%变量%。 例如,%hello% 是 另一个变量

问题:如何使用正则表达式执行此操作?

在 Javascript 中:

var repl = str.replace(/@('w+)/g, '%$1%');

在爪哇中:

String repl = str.replaceAll("@(''w+)", "%$1%");

在python中,为了完整性

import re
repl = re.sub(r'@('w+)', r'%'1%', strng)