简体   繁体   English

使用正则表达式查找字符串以$符号开头

[英]Find the String Starts with $ symbol using Regular Expression

String str = "hai ${name} .... Welcome to ${sitename}....";

from this str i need to replace ${name} by "jack" and ${sitename} by "google" 从这个str我需要用“jack”取代$ {name}而用“google”替换$ {sitename}

is it possible to do with regular Expression ? 是否可以使用正则表达式?

or 要么

is there any other fastest way to replace the string . 有没有其他最快的方法来替换字符串。

EDITED : 编辑:

name and sitename is the str variable is dynamic . name和sitename是str变量是动态的。

1.So first i have to find the key . 1.首先,我必须找到钥匙。
Eg : here name , sitename is the key 例如:这里的name , sitename是关键
2.Then i have an Hashmap which has key value pairs . 2.然后我有一个具有键值对的Hashmap。
based on the key value i have to replace the string in str variable. 基于键值我必须替换str变量中的字符串。

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Replacer
{
    public static String replacePlaceHolders(String text)
    {
        Map<String, String> fields = new HashMap<>();

        fields.put("name", "jack");
        fields.put("sitename", "google");

        Pattern p = Pattern.compile("\\$\\{(.*?)\\}");
        Matcher matcher = p.matcher(text);

        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String key = matcher.group(1);

            if (!fields.containsKey(key)) {
                continue;
            }

            matcher.appendReplacement(result, fields.get(key));
        }

        matcher.appendTail(result);

        return result.toString();
    }

    public static void main(String[] args)
    {
        System.out.println(
                replacePlaceHolders("hai ${name} .... Welcome to ${sitename}...."));
    }
}

NO Regex is needed! 不需要正则表达式!

You could iterate the keySet of your map, and do: 您可以迭代地图的keySet,并执行以下操作:

str=str.replace("${"+key+"}", map.get(key));

about the method: 关于方法:

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence , java.lang.CharSequence) http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence,java.lang.CharSequence

我认为你最好使用String.format

String str = String.format("hai %s .... Welcome to %s....", name, site);

Maybe this will help you: 也许这会对你有所帮助:

\$\{name+\}

change ${name} to test 更改$ {name}进行测试

-> ${name} trete ${sitename} -> test trete ${sitename} - > $ {name} trete $ {sitename} - > test trete $ {sitename}

You have to escape this expression for usage in Java: 您必须转义此表达式才能在Java中使用:

\\$\\{name+\\}

If you can replace ${name} and ${sitename} with {0} and {1} you could use MessageFormat . 如果您可以使用{0}{1}替换${name}${sitename} ,则可以使用MessageFormat

String str = "hai {0} .... Welcome to {1}....";
String output = MessageFormat.format(str, new String[]{"jack","google"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM