I am trying to validate the user input using the regular expression in JavaScript. Valid input are at least two characters with *
symbol. In other words valid format is
< '*' or nothing><at least two characters>< '*' or nothing>
So of the valid inputs are
Mu*
*pa
*pa*
And invalid inputs are
*e*
*e*t
*e*t*
pa**
I am trying following expression but not working.
^{\*}?[A-Za-z]{\*}?$
The definition isn't clear, but let's assume that a valid string must have either an initial or final *
character (ie, a string with no *
at all is invalid). Whether a final *
is required depends on the presence or absence of an initial *
. I suspect (though I haven't proven) that this means your set of valid strings cannot be described by a regular language.
Instead, your language can be described as the union of two regular langauges: one whose strings end (and optionally begin) with a *
and one whose strings begin (and optionally end) with a *
:
/^\*?\w{2,}\*$|^\*\w{2,}\*?$/
Here, we accept
*
(and an optional leading *
) or *
(and an optional final *
). Adjusted: ^\\*?\\w{2,}\\*?$
should do the trick.
Ooops: Just noticed the "hint" in @NiettheDarkAbsol comment - which gives basically the same solution.
However, we might both be wrong as all the examples for valid sequences do have at least one asterisk. Which is not explicit in the 'formal' description, though…
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.