Using Regular Expressions to Extract a Value in Java

前端 未结 13 1074
失恋的感觉
失恋的感觉 2020-11-22 13:08

I have several strings in the rough form:

[some text] [some number] [some more text]

I want to extract the text in [some number] using the

13条回答
  •  无人及你
    2020-11-22 13:44

    This function collect all matching sequences from string. In this example it takes all email addresses from string.

    static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
    
    public List getAllEmails(String message) {      
        List result = null;
        Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);
    
        if (matcher.find()) {
            result = new ArrayList();
            result.add(matcher.group());
    
            while (matcher.find()) {
                result.add(matcher.group());
            }
        }
    
        return result;
    }
    

    For message = "adf@gmail.com, >>> lalala@aaa.pl" it will create List of 3 elements.

提交回复
热议问题