简体   繁体   中英

Extract substring from string - regex

I have a String say:

<encoded:2,Message request>

Now I want to extract 2 and Message request from the line above.

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);

            }
        }
    }

This doesn't retrieve it. What is wrong with it

You have to define groups in your regex:

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

or

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

try

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

Try

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

Also, as suggested in other comments, use group(1) and group(2)

Try this out :

         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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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