user613114
user613114

Reputation: 2821

Regex: Allow minimum alphanumeric, dot and - characters. Asterisk allowed anywhere?

My requirement is that:

  1. String should contain minimum 4 characters (only alphanumeric, dot and hyphen allowed).
  2. Apart from this asterisk is allowed anywhere (start, in-between or end)
  3. It should not contain any other characters than mentioned in point 1 and 2 above.

e.g. following are valid strings:

Ab*08

*.6-*N*

following are invalid strings:

****AB-*

GH.*

My regex looks like:

^(.*?[a-zA-Z0-9.\-]){4,}.*$

My basic validations as mentioned in point 1 and 2 are working. But regex allows other special characters like <, >, & etc. How can I modify my regex to achieve this?

Upvotes: 2

Views: 2979

Answers (2)

Christian
Christian

Reputation: 4094

^(?:\**[\w\d.-]\**){4,}$

This should do it. A little bit simpler.

Upvotes: 0

Sebastian Proske
Sebastian Proske

Reputation: 8413

You can use

^(?:[*]*[a-zA-Z0-9.-]){4}[*a-zA-Z0-9.-]*$

It checks for 4 valid characters (that might be surrounded by *) and checks that your whole string only of your required characters.

Obligatory regex 101

Note: regex101 doesn't fully support java regex syntax. The pattern shown is a PCRE pattern, but all features used are also available in java regex.

Note2: if you use .matches to check your input, you can omit anchors, at it is already anchored.

Upvotes: 5

Related Questions