Regex allow asterisk(*) only once time and in the end

568 views Asked by At

I want to pass only the strings like this:

abc*
123*
abc 123*
abc-123abc*

I don't want to pass strings like those:

 - abc**
 - abc*123
 - *abc

The asterisk must be in the end and only once time.

With the regex like \* I get all asterisk, but i dont klnow how i specified. I am not so good in regex.

1

There are 1 answers

0
Wiktor Stribiżew On BEST ANSWER

You can use

^[^*]*\*$

Note it will also match a * string. If there must be at least two chars, replace the [^*]* part with [^*]+ to match one or more chars other than * before the final *.

See the regex demo. Details:

  • ^ - start of a string
  • [^*]* - zero or more chars other than *, as many as possible (greedily)
  • \* - a * char
  • $ - at the end of string.