使用正则表达式从字符串获取字符串

时间:2018-10-03 03:05:07

标签: java regex string

我正尝试使用下面的正则表达式获取所有amid键值,但是当我使用https://regex101.com/测试时,我只能匹配第一个amid键。

使用此Java Matcher时,没有任何结果:

List<String> allMatches = new ArrayList<String>();

Matcher m = Pattern
             .compile("("amid"): ("\w+\-*+")")
             .matcher(idValue);

while (m.find()) {
    allMatches.add(m.group());
    System.out.println("------oranges-------" + m.group(1));
}

正则表达式-("amid"): ("\w+\-*+")

我要去哪里错了?

{"link":"/us_new/en/home","amid":"1__home","title":"Home"},
{"link":"/us_new/en/home/diagnosis-and-treatment",
"amid":"2__diagnosis-and-treatment","title":"Diagnosis and treatment"},
{"link":"/us_new/en/home/diagnosis-and-treatment/diagnosing-hearing-loss",
"amid":"3__diagnosing-hearing-loss","title":"Diagnosing hearing loss"}

1 个答案:

答案 0 :(得分:0)

冒号后("amid"): ("\w+\-*+")中有一个空格。删除它,您的正则表达式就可以正常工作。

如果要捕获所有“ amid”标签,请使用正则表达式("amid"):("[\w,-]+")

    Matcher m = Pattern.compile("(\"amid\"):(\"[\\w,-]+\")").matcher("...")
    while (m.find()) {
        System.out.println(m.group());
    }

输出

"amid":"1__home"
"amid":"2__diagnosis-and-treatment"
"amid":"3__diagnosing-hearing-loss"