Reputation: 5
I am trying to split the below String on '-' but the problem is that the split should only happen '-' when it has characters on both the sides.
String s = "1 - 2 Foo - Bar 3 - 4 Wrong - Right"
Ouptut
String[0] = 1 - 2 Foo
String[1] = Bar 3 - 4 Wrong
String[2] = Right
Is there any way to achieve this.
Upvotes: 0
Views: 69
Reputation: 271750
You can use this regex:
(?<=[a-zA-Z]) - (?=[a-zA-Z])
like this:
s.split("(?<=[a-zA-Z]) - (?=[a-zA-Z])")
Explanation:
(?<=...)
is a positive lookbehind, it checks to see if the stuff before the hyphen matches [a-zA-Z]
, but doesn't actually matches them. The (?=...)
is similar, but it looks ahead to see if the stuff on the right of the hyphen matches [a-zA-Z]
.
Upvotes: 8