Hatefiend
Hatefiend

Reputation: 3596

Regex to match a period but not if there is a period on either side (Java)

I'm looking for a regex that will match a period character, ONLY if none of that period's surrounding characters are also periods.

 Fine by me... leave!    FAIL

 Okay.. You win.     SUCCEED

 Okay. SUCCEED //Note here, the period is the last char in the string.

I was thinking do:

 [^\\.*]\\.       

But that is just wrong and probably not at all in the right direction. I hope this question helps others in the same situation as well.

Thanks.

Upvotes: 3

Views: 3374

Answers (3)

Bohemian
Bohemian

Reputation: 425033

You need to wrap the dot in negative look arounds:

(?<![.])[.](?![.])

I prefer [.] over \\., because:

  1. It's easier to read - there are too many back slashes in java literals already
  2. [.] looks a bit like an X wing fighter from Star Wars ™

Upvotes: 5

SnoProblem
SnoProblem

Reputation: 1939

That regex will still match any period that isn't preceded by another period.

[^\.]\.[^\.] Takes care of both sides of the target period.

EDIT: Java doesn't have a raw string like Python, so you would need full escapes: [^.]\\.[^.]|^\\.[^.]|[^.]\\.$

Upvotes: 0

dev.null
dev.null

Reputation: 538

You can use negative look ahead and look behind or this alternative regex:

String regex = "(^\\.[^\\.]|[^\\.]\\.[^\\.]|[^\\.]\\.$)";

The first alternative check the beginning ^ of the string (if it can start with a dot), the second looks for any dot inside and the third looks for a dot at the end of the string $.

Upvotes: 0

Related Questions