从字符串中提取子字符串 - 正则表达式

时间:2013-03-25 09:42:46

标签: java regex

我有一个字符串说:

<encoded:2,Message request>

现在我想从上面的行中提取2Message request

private final String pString = "<encoded:[0-9]+,.*>";
    private final Pattern pattern = Pattern.compile(pString);

    private void parseAndDisplay(String line) {

        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            while(matcher.find()) {
                String s = matcher.group();
                System.out.println("=====>"+s);

            }
        }
    }

这不会检索它。有什么问题

4 个答案:

答案 0 :(得分:6)

您必须在正则表达式中定义组:

"<encoded:([0-9]+),(.*?)>"

"<encoded:(\\d+),([^>]*)"

答案 1 :(得分:4)

    String s = "<encoded:2,Message request>";
    String s1 = s.replaceAll("<encoded:(\\d+?),.*", "$1");
    String s2 = s.replaceAll("<encoded:\\d+?,(.*)>", "$1");

答案 2 :(得分:0)

尝试

"<encoded:([0-9]+),([^>]*)"

另外,正如其他评论中所建议的那样,请使用group(1)group(2)

答案 3 :(得分:0)

试试这个:

         Matcher matcher = Pattern.compile("<encoded:(\\d+)\\,([\\w\\s]+)",Pattern.CASE_INSENSITIVE).matcher("<encoded:2,Message request>");

    while (matcher.find()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
    }