[英]I want to extract all substring that match regex pattern from a String and store them in a String array
我想提取所有有异常的子字符串。 例如,来自以下字符串的“SQLException”、“SQLSyntaxErrorException”等,并将这些值存储在字符串数组中。 我该怎么做 go 呢? 我尝试使用 split(regex) 方法,但它将所有其他内容存储在数组中,但不存储那些异常。 帮助表示赞赏。
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);
尝试这个:
String input = <exception list...>
String regex = "\\w+Exception";
Matcher m = Pattern.compile(regex).matcher(input);
while (m.find()) {
System.out.println(m.group());
}
印刷
SQLException
SQLGrammarException
SQLGrammarException
SQLSyntaxErrorException
要将它们放入数组中,请执行以下操作:
String[] array = m.results()
.map(MatchResult::group)
.toArray(String[]::new);
m.results()
产生MatchResults
的stream
。 因此,采用该方法并使用group
方法获取字符串,然后返回一个数组。
正如Abra敏锐地观察到的那样,直到 JDK 9 发行版才引入上述内容。
这是一个替代方案。
List<String> list = new ArrayList<>();
while (m.find()) {
list.add(m.group());
}
然后用作列表或转换。
String[] array = list.stream().toArray(String[]::new);
// or
String[] array = list.toArray(String[]::new); // JDK 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.