简体   繁体   中英

How to parse this string in Java

I would like to understand how you would parse the below string in Java. Basically, I want everything between the text "Begin-Data" and "End-Data"

Begin-Data
abc
123
End-Data

A one-liner solution uses String#replaceAll :

String input = "Begin-Data abc 123 End-Data";
String output = input.replaceAll("(?s).*\\bBegin-Data\\s+(.*?)\\s+End-Data\\b.*", "$1");
System.out.println(output);  // abc 123

This answer assumes that the input string only contains the starting/ending tags Begin-Data and End-Data once. If you have many such tags, then you should use a formal regex pattern matcher:

String input = "Begin-Data abc 123 End-Data Begin-Data abc 345 End-Data";
String pattern = "(?s)\\bBegin-Data\\s+(.*?)\\s+End-Data\\b";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
List<String> matches = new ArrayList<>();

while (m.find( )) {
    matches.add(m.group(1));
}
System.out.println(matches);  // [abc 123, abc 345]

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