Reputation: 3596
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
Reputation: 425033
You need to wrap the dot in negative look arounds:
(?<![.])[.](?![.])
I prefer [.]
over \\.
, because:
[.]
looks a bit like an X wing fighter from Star Wars ™Upvotes: 5
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
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