简体   繁体   中英

Regular expression in JavaScript to match wildcard

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

  • minimum two-letter strings with a required final * (and an optional leading * ) or
  • minimum two-letter strings with a required leading * (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…

Is it not simply this?

/^\\*?[a-zA-Z]{2,}\\*?$/

http://regex101.com/r/gT3nY4/1

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM