PaulStrom
PaulStrom

Reputation: 23

Regular Expression. Only a dot

I'm trying to write a regular expression:

Pattern pattern2 = Pattern.compile("^([a-zA-Z0-9_'.-]{2,15})$");
Matcher matcher2 = pattern2.matcher(username); 

what it should do is:

- all letters are allowed
- all digit are allowed
- symbols such as _'- are allowed

I would like to add that only a dot is allowed.

user.name      ok
use.rna.me     not ok

Thank u a lot for the help!

Upvotes: 0

Views: 96

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can achieve that with a lookahead anchored at the start:

"^(?=[^.]*\\.[^.]*$)[a-zA-Z0-9_'.-]{2,15}$"
  ^^^^^^^^^^^^^^^^^^

Also, you can use \w instead of [a-zA-Z0-9_] (if you do not add the (?U) inline modifier or the Pattern.UNICODE_CHARACTER_CLASS flag):

"^(?=[^.]*\\.[^.]*$)[\\w'.-]{2,15}$"

However, the patterns above will require 1 dot in the string. If a dot is not required, reverse the requirement: fail the match if 2 dots are present:

"^(?![^.]*\\.[^.]*\\.)[\\w'.-]{2,15}$"
  ^^^^^^^^^^^^^^^^^^^^ 

Pattern details:

  • ^ - start of string
  • (?![^.]*\\.[^.]*\\.) - negative lookahead that fails the match if there are 0+ characters other than . from the start, followed with a . and then again 0+ characters other than . from the start, followed with a . (NOTE that this can be shortened as (?!(?:[^.]*\\.){2}).
  • [\\w'.-]{2,15} - 2 to 15 characters, either a word one ([a-zA-Z0-9_]) or
  • . or a hyphen
  • $ - end of string.

Upvotes: 2

SamWhan
SamWhan

Reputation: 8332

You could do it with

^(?=.{2,15}$)[\w-']*\.?[\w-']*$

First it makes sure the whole expression is 2-15 characters long with a positive look-ahead. Then it matches any number of word characters (a-z, A-Z, 0-9 and _), followed by an optional dot, and again followed by any number of word characters. The anchors (^ - start of line, $ - end of line) ensures nothing else is present.

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

You can try a negative-lookahead

    String p = "use.rname";
    System.out.println(p.matches("(?!.*?\\..*?\\..*)([a-zA-Z0-9_'.-]{2,15})"));

O/P :

"use.rname" ==> true
"use.rname.xyz" ==> false

Upvotes: 1

Related Questions