vikas bhosale
vikas bhosale

Reputation: 5

Splitting of String on encountering '-' between characters but not on numbers

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

Answers (1)

Sweeper
Sweeper

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

Related Questions