简体   繁体   English

JavaScript中的正则表达式以匹配通配符

[英]Regular expression in JavaScript to match wildcard

I am trying to validate the user input using the regular expression in JavaScript. 我正在尝试使用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 * ). 至少两个字母的字符串,带有必需的前导* (和可选的final * )。

Adjusted: ^\\*?\\w{2,}\\*?$ should do the trick. 调整: ^\\*?\\w{2,}\\*?$应该可以解决问题。
Ooops: Just noticed the "hint" in @NiettheDarkAbsol comment - which gives basically the same solution. 糟糕:刚刚注意到@NiettheDarkAbsol注释中的“提示”-基本上提供了相同的解决方案。
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 http://regex101.com/r/gT3nY4/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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