Bug
Bug

Reputation: 942

Regular Expression to match a single word separated by dot or only allow asterisk

I need a regular expression that allows only one asterisk or a work separated by dot and one asterisk at the end. For example:

test.test   = OK
test.test*  = OK
*           = OK

.                       = NO
_                       = NO
test.*                  = NO
test.test               = OK
test.test2              = OK
test*                   = OK
te*st                   = NO
test*.test              = NO

This is what I did so far

^[a-z0-9*.\-_\.:]+$

The non character to allow are dots and one asterisk The character to allow are lower case

Upvotes: 0

Views: 1600

Answers (2)

Alberto Chiesa
Alberto Chiesa

Reputation: 7360

So you want either:

  • 1 asterisk or
  • a dot separated sequence of words, only the last of which can be followed by an asterisk

^((\*)|([a-zA-Z0-9]+)(\.[a-zA-Z0-9]+)*\*?)$

Please note that [a-zA-Z0-9]+ should be adapted to what you really mean as a word. In my answer it is simply one or more alfanumeric chars.

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can use this one

^[a-zA-Z0-9]+?\.?[a-zA-Z0-9]+?\*?$|^\*$
  • ^ - Start of string.
  • [a-zA-Z0-9]+? - Matches any alphabet or digit one or more time (lazy mode).(? makes it optional)
  • \.? - Matches . .
  • \*? - Matches *.
  • $ - End of string.
  • | - Alternation.
  • ^\*$ - Matches *.

Demo

Let me know if i missed any case.

Upvotes: 2

Related Questions