java - 将字符串中的正则表达式模式替换为取决于匹配的替换字符串

标签 java javascript python regex

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

示例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/

相关文章:

java - 驱动程序文件中缺少 JxBrowser BrowserFactory

java - 如何将集合属性绑定(bind)到 Spring MVC 中的表单

javascript - JavaScript API 接口(interface)前缀的方法?

javascript - 函数($)和$(函数())之间的区别

javascript - 如何在爬行时绕过robots.txt

python - GTK 3 中的行删除按钮

java - 从 Firebase 检索数据时出错

java - 安卓启动屏幕

python - 如何找到重新排序的 numpy 数组的索引?

python - 将包含毫秒的特殊时间戳转换为纪元