Canttouchit
Canttouchit

Reputation: 3159

How to prevent char repetition with Java regex

I try to prevent repetition of the dot char '.' and allowing only numbers/letters

e.g.

"blah...blah".matches(rex)) //false
 "..blablah".matches(rex)) //false
"blablah..".matches(rex)) //false
"blab.lah".matches(rex)) //true
"bla.blah".matches(rex)) //true

I tried using: ^(?!\.\.)([a-zA-Z0-9._\-]*)$ but it works only for the second example, how can I make it work?

Upvotes: 2

Views: 522

Answers (3)

Bohemian
Bohemian

Reputation: 425003

Use a back-reference to a captured character:

if (str.matches("(([\\w.-])(?!\\2))*"))
    // no chars are repeated

See live demo.

Note that "letters, numbers, underscore, dot and dash" can be written as [\\w.-].
\w == [a-zA-Z0-9_] and the dash doesn't need escaping if it appears first or last.

Upvotes: 2

Sebastian Proske
Sebastian Proske

Reputation: 8413

You were quite close, you need to adjust the lookahead to (?!.*\\.{2}), so the overall regex is ^(?!.*\\.{2})([a-zA-Z0-9._\-]*)$. Note that you don't need the anchors when used with .matches() as it tries to match the whole string.

If you don't want any of the non-letters/numbers to consecutively repeat, you can instead use (?!.*([._-])\\1+) for the lookeahed.

Upvotes: 2

ItamarG3
ItamarG3

Reputation: 4122

Use String.replace() to remove all the '.' characters.

String a="blah...blah";
a = a.replace(".", "");
System.out.println(a);

the output of this is blahblah.

Upvotes: 0

Related Questions