String a="username=mrluo|age=35|ps=word";
String b="my name is [username] and age is [age] ps is[ps]";
String result;有这样的两个字符串。我想遍历b去找a的值,中间空格什么的不用考虑,只是吧"[]"替换成值就行了,效果如下
result="my name is mrluo and age is 35 ps is word"有没有会正则的,那就牛死,大家玩玩吧

解决方案 »

  1.   

    String a="username=mrluo|age=35|ps=word";
    String b="my name is [username] and age is [age] ps is[ps]";
    String result = null;

    String username = a.substring(a.indexOf("username") + "username".length() + 1, a.indexOf("|age"));
    String age = a.substring(a.indexOf("age") + "age".length() +1, a.indexOf("|ps"));
    String ps = a.substring(a.indexOf("ps") + "ps".length() + 1);


    if(b.indexOf("username") != -1)
    {
    b = b.replace("[username]", username);
    }
    if(b.indexOf("age") != -1)
    {
    b = b.replace("[age]", age);
    }
    if(b.indexOf("ps") != -1)
    {
    b = b.replace("[ps]", ps);
    }
    result = b;
    System.out.println("result" + ":" + result);
      

  2.   

    正则不太会用,你看这样OK不.import java.util.HashMap;
    import java.util.Map;public class Test {
    public static void main(String[] args) {
    String a = "username=mrluo|age=35|ps=word";
    String[] strs = a.split("\\|");
    Map<String, String> map = new HashMap<String, String>();
    for (String str : strs) {
    String[] keyValue = str.split("=");
    if (keyValue.length == 2) {
    map.put(keyValue[0], keyValue[1]);
    }
    }

    String b = "my name is [username] and age is [age] ps is[ps]";
    b = b.replaceAll("\\[username\\]", map.get("username")).replaceAll("\\[age\\]", map.get("age")).replaceAll("\\[ps\\]", map.get("ps"));
    System.out.println(b);
    }
    }
      

  3.   

    String a="username=mrluo|age=35|ps=word";
    String b="my name is [username] and age is [age] ps is [ps]"; String reg = "\\[(.+?)\\](?=.+?\\1\\=(.+?)(\\||$))";
    String c = (b+a).replaceAll(reg, "$2");
    System.out.println(c.substring(0,(c.length()-a.length())));
      

  4.   

    public static void main(String[] args) throws Exception { String a = "username=mrluo|age=35|ps=word";
    String b = "my name is [username] and age is [age] ps is [ps]";
    String[] arr = a.replaceAll(" {1,}", "").split("\\|");
    for (String s : arr) {
    b = b.replaceFirst("\\[.+?\\]", s.split("=")[1]);
    }
    System.out.println(b); }
      

  5.   


    String result = MessageFormat.format("my name is {0} and age is {1} ps is{2}", "mrluo",35,"word");
    System.out.println(result);换种思路可以么?这样的.