简体   繁体   English

正则表达式用于特定数字或特定单词

[英]Regex for a specific number or specific word

For a security question on a form, I want the user to enter either 4 or four , or any variation of the latter. 对于表单上的安全性问题,我希望用户输入4four或后者的任何变体。

Right now I have this regex /\\b4|four\\b/gi that is a variation of one I've found on this site. 现在,我有这个正则表达式/\\b4|four\\b/gi ,它是我在此站点上找到的正则表达式的变体。 The problem is that the user can enter 458 or something. 问题是用户可以输入458或其他内容。 So, can somebody help me out? 那么,有人可以帮我吗?

I'm not sure what you mean by "any variation of the latter", but: 我不确定“后者的任何变化”是什么意思,但是:

/^(4|four)$/i

will match the entire string being either 4 or four. 将匹配整个字符串(4或4)。 The ^ matches only at the start and $ only at the end. ^仅在开头匹配, $仅在结尾匹配。 /i means case insensitive (so FOUR would be accepted as well). /i表示不区分大小写(因此也将接受四)。 Some languages don't take flags like that (in them, you'll have to check the docs on how to do an insensitive match). 某些语言不会带有这样的标志(在其中,您必须检查有关如何进行不敏感匹配的文档)。 If you can't use a case-insensitive match, you can do this instead: 如果您不能使用不区分大小写的匹配,则可以执行以下操作:

/^(4|[fF][oO][uU][rR])$/i

Of course, whatever language you're working in probably also has equality comparisons. 当然,无论您使用哪种语言,都可能会进行相等比较。 So you could just do (for example) 所以你可以做(​​例如)

if (str == "4" || str == "four")

Try: 尝试:

^4|four$

which will match "4" and "four". 它将匹配“ 4”和“四个”。 Depending on the programming language that you use there might be a case insensitive option like C#'s RegexOptions.IngoreCase 根据您使用的编程语言,可能会有不区分大小写的选项,例如C#的RegexOptions.IngoreCase

So you should be using a case-insensitve comparison for this. 因此,您应该对此使用不区分大小写的比较。 Some (perhaps most) regex flavors will support the pattern (?i) to denote case insensitivity. 某些(也许大多数)正则表达式香料将支持模式(?i)以表示不区分大小写。

^(?i)(?:4|four)$

But if this is JavaScript then you can use a syntax more like what you started with... 但是,如果这是JavaScript,那么您可以使用与开始时一样的语法...

/^(?:4|four)$/i

The /i is for case insensitivity in this case. 在这种情况下, /i用于区分大小写。 But I removed /g since it's for global matching and wouldn't be needed here. 但是我删除了/g因为它是用于全局匹配的,在这里不需要。

Notice that I also put 4|four inside a (?:non capturing) group. 请注意,我还在(?:non capturing)组中放入了4|four This is more efficient than using a traditional (capturing) group when you don't need to do anything with the captured value. 当您不需要对捕获的值做任何事情时,这比使用传统的(capturing)组更有效。

Then the ^ and $ anchors surrounding everything will ensure you have no extra leading or following characters. 然后,围绕所有内容的^$定位符将确保您没有多余的前导或后继字符。

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

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