0

I want to extract all the substrings that have Exceptions. For example, "SQLException", "SQLSyntaxErrorException" etc from the below string, and store those values in a String array. How do I go about it? I tried to use the split(regex) method but that stores everything else in the array but not those exceptions. Help is appreciated.

public static void exceptionsOutOfString(){
    String input = "org.hibernate.exception.SQLException: error executing work org.hibernate.exception.SQLGrammarException: error \n" +
            "executing work     at  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]     \n" +
            "\\norg.hibernate.exception.SQLGrammarException: error executing work     at  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final] \n" +
            "     Caused by: java.sql.SQLSyntaxErrorException: malformed string: 'Acme''    at";

    String regex = ".[a-zA-Z]*Exception";

    String[] exceptions  = input.split(regex);
1
  • Please show exactly what strings you expect to capture Commented Jul 24, 2020 at 22:54

1 Answer 1

2

Try this:

String input = <exception list...>
String regex = "\\w+Exception";
Matcher m = Pattern.compile(regex).matcher(input);

while (m.find()) {
    System.out.println(m.group());
}

Prints

SQLException
SQLGrammarException
SQLGrammarException
SQLSyntaxErrorException

To put them in an array, do the following:

String[] array = m.results()
             .map(MatchResult::group)
             .toArray(String[]::new);

m.results() produces a stream of MatchResults. So take that and use the group method to get the string then return an array.

As was astutely observed by Abra, the above was not introduced until release JDK 9.

Here is an alternative.

List<String> list = new ArrayList<>();
while (m.find()) {
     list.add(m.group());
}

Then either use as a list or convert.

String[] array = list.stream().toArray(String[]::new);
// or
String[] array = list.toArray(String[]::new); // JDK 11
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. How do i put the results of the matcher in a String[] array?
Perhaps you should mention that method results() was added to class Matcher in JDK 9?
Thanks @WJS that works. Thanks for your help!! I was asked this question and the guy had a one line solution for extracting the regex matches from the string and store them in an array. I just can't remember what he did! :(

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.