I have this string: "123456 - A, Bcd, 789101 - E, Fgh"
I want it split into: "123456 - A, Bcd" and "789101 - E, Fgh". How can I achieve this? What regex
and split
expressions should I use?
I see I can find the comma after "Bcd" using .matches(".*[az],\\\\s[0-9].*")
but how do I split the strings ONLY at that comma? .split(",\\\\s")
splits at all occurring comma followed by space...
I work with JAVA 1.6.
You may split on the comma that is followed with 0+ whitespaces, 6 digits, space and a hyphen:
String[] result = s.split(",\\s*(?=\\d{6} -)");
See the regex demo .
Pattern details
,
- a comma \\s*
- 0+ whitespace chars (?=\\\\d{6} -)
- a positive lookahead (a non-consuming pattern, what it matches won't be part of the result) that requires 6 digits followed with a space and -
immediately to the right of the current location.
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.