我有一个包含变量的特殊字符串。任何以“@”符号开头的单词都是该字符串中的变量。
示例foostring:
This is my string and this is a @variable in it. Example, @hello is another variable
我想执行一个操作,将此类特殊字符串中的任何通用变量 @-variable- 替换为 %-variable-%。
因此上面的示例 foostring 字符串将变成这样(在此操作之后):
This is my string and this is a %variable% in it. Example, %hello% is another variable
问题: 如何使用正则表达式执行此操作?
最佳答案
在 JavaScript 中:
var repl = str.replace(/@(\w+)/g, '%$1%');
在 Java 中:
String repl = str.replaceAll("@(\\w+)", "%$1%");
为了完整起见,在Python中
import re
repl = re.sub(r'@(\w+)', r'%\1%', strng)
关于java - 将字符串中的正则表达式模式替换为取决于匹配的替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19401236/