java正则表达式查找和替换 [英] java regular expression find and replace

查看:3419
本文介绍了java正则表达式查找和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在输入中找到环境变量并用值替换它们。

I am trying to find environment variables in input and replace them with values.

env变量的模式是 $ {\\\ \\。}

The pattern of env variable is ${\\.}

Pattern myPattern = Pattern.compile( "(${\\.})" );
String line ="${env1}sojods${env2}${env3}";

如何用<$替换 env1 c $ c> 1 和 env2 2 env3 3 ,所以
之后我会有一个新字符串 1sojods23

How can I replace env1 with 1 and env2 with 2 and env3 with 3, so that after this I will have a new string 1sojods23?

推荐答案

Java中的字符串是不可变的,如果你在谈论你需要的任意数量的东西,这有点棘手找到并替换。

Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace.

具体来说,您需要在 Map 中定义替换,使用 StringBuffer 匹配器的code>和 appendReplacements() appendTail()方法/ code>。最终结果将存储在 StringBuffer 中。

Specifically you need to define your replacements in a Map, use a StringBuffer and the appendReplacements() and appendTail() methods from Matcher. The final result will be stored in your StringBuffer.

Map<String, String> replacements = new HashMap<String, String>() {{
    put("${env1}", "1");
    put("${env2}", "2");
    put("${env3}", "3");
}};

String line ="${env1}sojods${env2}${env3}";
String rx = "(\\$\\{[^}]+\\})";

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(rx);
Matcher m = p.matcher(line);

while (m.find())
{
    // Avoids throwing a NullPointerException in the case that you
    // Don't have a replacement defined in the map for the match
    String repString = replacements.get(m.group(1));
    if (repString != null)    
        m.appendReplacement(sb, repString);
}
m.appendTail(sb);

System.out.println(sb.toString());

输出:

1sojods23

这篇关于java正则表达式查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆