Given is the following string (one line):
a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207
I would like to split it like this [611, 559, 446 ,1200], [597, 762, 448, 1101], [597, 558, 488, 1207] So basically to get the 4 numbers between each ":" and "," regardless of the characters between the numbers.
I already tried to split the string on "," but then I still have the problem of the number in front of ":". Or the all go together like using string result = Regex.Replace(input, @"[^\\d]", "");
Is there a way to do it with regex? Thanks in advance.
You can first use this regex \\d+x\\d+(?:\\+\\d+){2}
to match those numbers separated by x
and +
and then split those individual strings using [x+]
which will give you another array of numbers.
Check this Java code,
String s = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
Pattern p = Pattern.compile("\\d+x\\d+(?:\\+\\d+){2}");
List<List<String>> list = new ArrayList<>();
Matcher m = p.matcher(s);
while(m.find()) {
String[] data = m.group().split("[x+]");
list.add(Arrays.asList(data));
}
list.forEach(System.out::print);
Prints the output like you expected,
[611, 569, 446, 1200][597, 762, 448, 1101][597, 558, 488, 1207]
Use a Matcher
and its .find() method :
package so21090424;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternFinder {
public static void main(String[] args) {
final String input = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
Pattern p = Pattern.compile(":([0-9]+)[x\\+]([0-9]+)[x\\+]([0-9]+)[x\\+]([0-9]+),?");
Matcher m = p.matcher(input);
while(m.find()) {
System.out.println(m.group(1) + "\t" + m.group(2) + "\t" + m.group(3) + "\t" + m.group(4));
}
}
}
String input = "a_Type_of_Data 0.847481:611x569+446+1200,0.515323:597x762+448+1101,0.587354:597x558+488+1207";
List<List<String>> result = Arrays.stream(input.split(",")) // split input at ','
.map(e->e.split(":")[1]) // split each part at ':' and keep the second part
.map(e->Pattern.compile("[+x]").splitAsStream(e).collect(Collectors.toList())) // split at '+' or 'x' & collect to list
.collect(Collectors.toList()); // collect to list
System.out.println(result);
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.