Zuriar
Zuriar

Reputation: 11734

How to split a string on a 'dot' if, and only if, the preceding and following char is not a 'dot'

Given the following string:

"foo.bar.baz"

it can be split on the 'dot' easily enough using Java String split:

split("foo.bar.baz", "\.")

However, if I want to conserve the dot if it is immediately followed by another dot, what is the regex expression:

"foo.bar.baz..raz..daz.faz" → "foo" "bar" "baz..raz..daz" "faz"

Upvotes: 0

Views: 852

Answers (1)

Maljam
Maljam

Reputation: 6274

This regex would work:

s.split("(?<!\\.)\\.(?!\\.)");  

The idea is to use negative lookahead to only split at "." which is not followed or preceded by another dot.

Upvotes: 7

Related Questions