A. Jachs
A. Jachs

Reputation: 47

Splitting string only at the first matching regex position

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(".*[a-z],\\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.

Upvotes: 1

Views: 65

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626851

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.

Upvotes: 4

Related Questions