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.
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]
.
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.