Reputation: 371
I use this regex \\wx\\w\\w\\w\\w
to split a string. I'm attempting to match 0x0441,a,2,3,4
and 0x0442,f,dws,212
from the following string : "0x0441,a,2,3,4,0x0442,f,dws,212"
Using the regex with code below :
import java.io.IOException;
import java.util.Arrays;
public class ReadLine {
public static void main(String args[]) throws IOException {
final String str = "0x0441,a,2,3,4,0x0442,f,dws,212";
Arrays.stream(str.split("\\wx\\w\\w\\w\\w")).forEach(split -> System.out.println(split));
}
}
prints :
,a,2,3,4,
,f,dws,212
I expect the output to be :
0x0441,a,2,3,4,
0x0442,f,dws,212
How to also capture the matched values 0x0441
& 0x0442
?
Upvotes: 1
Views: 46
Reputation: 89224
Use a positive lookahead:
Arrays.stream(str.split("(?=\\wx\\w\\w\\w\\w)"))
.forEach(System.out::println);
Note that your regular expression can be written more simply with a quantifier (as mentioned by Arvind Kumar Avinash).
Arrays.stream(str.split("(?=\\wx\\w{4})"))
.forEach(System.out::println);
Upvotes: 4