Arian
Arian

Reputation: 7719

Regex: All alphanumeric with at most one dot in the middle

I want to have a regex that

  1. contains alphanumeric characters and at most one dot
  2. only start with alpha character
  3. doesn't finish with dot

I tried:

 ^(?=.{8,})[a-zA-Z0-9^]([-_.][a-zA-Z0-9]*)?[a-zA-Z0-9^]$

which doesn't work, i.e. it doesn't match kjh.jhhhmnbmnb

Upvotes: 1

Views: 2796

Answers (3)

Try this:

^[A-Za-z][A-Za-z0-9]*(\.[A-Za-z0-9]+)?$

This could probably be more concise, but it requires a letter at first followed by an arbitrary number of alphanumeric characters. After that, there's (optionally) a period followed by more alphanumeric characters.

Upvotes: 4

Ted Hopp
Ted Hopp

Reputation: 234795

Try this:

^\p{IsAlphabetic}\w*(\.\w+)?$

That matches an alphabetic character first, then any number of word characters, then, optionally, a single dot followed by at least one word character.

If your version of Java doesn't support the Unicode character classes defined in Java's Pattern class, you can do this using Posix classes:

^\p{Alpha}\w*(\.\w+)?$

or, failing all else, your own explicit classes:

^[a-zA-Z][a-zA-Z_0-9]*(\.[a-zA-Z_0-9]+)?$

(Note that I've allowed the _ character to be consistent with Java's definition of what constitutes a "word" character (\w). Just remove it if not desired.)

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

Try the following regex:

^(?!.*\\..*\\..*)[A-Za-z]([A-Za-z0-9.]*[A-Za-z0-9])?$

Explanation:

(?!.*\\..*\\..*)   Assert that two periods do not occur
[A-Za-z]           Match an initial alpha character
(
[A-Za-z0-9.]*      Match an alphanumeric or dot zero or more times
[A-Za-z0-9]        Match a terminal alphanumeric only once
)?                 The entire quantity occurring zero or once

Code sample:

String input = "a23.d";
if (input.matches("^(?!.*\\..*\\..*)[A-Za-z]([A-Za-z0-9.]*[A-Za-z0-9])?$")) {
    System.out.println("match");
}

Upvotes: 1

Related Questions