I want to extract some string surrounded by certain patterns.
For Instance, the original String something like 1234@{78}dasdh@{1}fdsfs@{fdf}ad@{
and I want extract 78
, 1
, fdf
from it.
Below is my code for the purpose
public class Test {
// want to get "78", "1", "fdf"
private static String targetStr = "1234@{78}dasdh@{1}fdsfs@{fdf}ad@{";
public static void main (String[] args) throws Exception {
List<String> parsed = new ArrayList<>();
Pattern open = Pattern.compile("@\\{");
Matcher oMatcher = open.matcher(targetStr);
Pattern close = Pattern.compile("}");
Matcher cMatcher = close.matcher(targetStr);
while(oMatcher.find()) {
if(cMatcher.find()) parsed.add(targetStr.substring(oMatcher.start() + 2, cMatcher.start()));
}
System.out.println(parsed);
}
}
Is there anyway to complete this task? Some how it feels unsafe since use 2 iterator without any validation.