0

I have a outlook message with body. I need to get strings of certain pattern S15345,S15366 etc.

How can i achieve this in java?

I tried giving like below,

 String array[] = body.split("[S[0-9]]");
1
  • What Strings are you trying to create and place into in the array? And why not simply split on the comma?: body.split(",");? Commented Jun 16, 2018 at 22:47

1 Answer 1

3

In this case better way is to use Pattern Matcher with this regex S\d{5} or if the pattern can contain one or more digits you can use S\d+ instead

String body = ...
Pattern pattern = Pattern.compile("S\\d{5}");
Matcher matcher = pattern.matcher(body);
List<String> result = new ArrayList<>();
while (matcher.find()){
    result.add(matcher.find());
}

If you are using Java 9+ you can use :

String body = ...
List<String> result = Pattern.compile("S\\d{5}")
        .matcher(body)
        .results()
        .map(MatchResult::group)
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.