Match a character exactly once with regex

How can I match a character exactly once with a regex in Java? Let's say I want to look for strings which contain exactly one time the digit 3, and it doesn't matter where it is.

I tried to do this with ".*3{1}.*" but obviously this will also match "330" as I specified with the period that I don't care what character it is. How can I fix this?

Upvotes: 0

Views: 10047

Answers (2)

Alexis C.
Alexis C.

Reputation: 93892

A non-regex solution:

int index = s.indexOf('3');
boolean unique = index != -1 && index == s.lastIndexOf('3');

Basically the character is unique if the first and last occurrences are at the same place and exist in the string (not -1).

Upvotes: 4

Will Harris
Will Harris

Reputation: 94

^[^3]*3[^3]*$

Match (not three), then three, then (not three).

Edit: Adding ^ and $ at beginning and end. This will force the regex to match the whole line. Thanks @Bobbyrogers and @Mindastic

Upvotes: 6

Related Questions