首页 > 解析出字符串中的特定值

解析出字符串中的特定值

"你好,{#username#},你的宝贝{#goods#}已由{#express#}"于{#time#}发出,请注意收货。联系电话{#phone#}。"

从以上文本中想获得"username,goods,express,time,phone"的字符串(注意用逗号隔开),或者包含上述字符串的数组。
请用JS和java分别实现,谢谢!


打开chrome控制台(F12键),在控制台输入以下内容:

var s12 = "你好,{#username#},你的宝贝{#goods#}已由{#express#}于{#time#}发出,请注意收货。联系电话{#phone#}。"
var reg2 = /{#(\w+)#}/g;
var results=[];
var tmp;
while((tmp=reg2.exec(s12)) != null){results.push(tmp[1])}
console.log(results);

结果输出:["username", "goods", "express", "time", "phone"]

原理:
正则表达式/{#(\w+)#}/g中括号之间定义的部分是一个分组,是我们希望提取的值。
但是注意的是,整个正则表达式也是一个分组,这就是为什么调用reg2.exec返回的是一个数组,数组中第一项就是整个正则表达式对应的分组,第二个才是我们定义的那个分组(\w+),当exec没有匹配到时就会返回null。


Java 版的

@WestFarmer 已经写了 javascript 的,我来补 java 的

public static List<String> getNames(String s) {
    Pattern pattern = Pattern.compile("\\{#(\\w+)#\\}");
    Matcher m = pattern.matcher(s);

    List<String> result = new ArrayList<String>();
    while (m.find()) {
        result.add(m.group(1));
    }
    return result;
}

测试

public static void main(String[] args) {
    String s = "你好,{#username#},你的宝贝{#goods#}已由{#express#}于{#time#}发出,请注意收货。联系电话{#phone#}。";

    for (String name : getNames(s)) {
        System.out.println(name);
    }
}

输出

username
goods
express
time
phone
【热门文章】
【热门文章】