简体   繁体   English

正则表达式创建允许,不允许几个字符

[英]Regex creation to allow, disallow few characters

I am new to regex, i have this use case:我是正则表达式的新手,我有这个用例:

  1. Allow characters, numbers.允许字符、数字。
  2. Zero or one question mark allowed.允许零个或一个问号。 (? - valid, consecutive question marks are not allowed (??)). (? - 有效,不允许连续问号 (??))。

test-valid测试有效

?test - valid ? 测试 - 有效

??test- invalid ??test-无效

?test?test - valid ?test?test - 有效

???test-invalid ???测试无效

test??test -invalid测试?测试 - 无效

  1. Exlcude $ sign.排除 $ 符号。

[a-zA-Z0-9?] - seems this doesn't work [a-zA-Z0-9?] - 似乎这不起作用

Thanks.谢谢。

Try the following regular expression:试试下面的正则表达式:
^(?!.*\\?\\?)[a-zA-Z0-9?]+$

  1. first we're using Negetive lookahead - which allows us to exclude any character which is followed by double question marks ( Negetive lookahaed does not consume characters)首先,我们使用Negetive lookahead - 这允许我们排除任何后跟双问号的字符( Negetive lookahaed不消耗字符)

  2. Since question mark has special meaning in regular expressions ( Quantifier — Matches between zero and one times), each question mark is escaped using backslash.由于问号在正则表达式中具有特殊含义( Quantifier — 匹配零次和一次),因此每个问号都使用反斜杠进行转义。

  3. The plus sign at the end is a Quantifier — Matches between one and unlimited times, as many times as possible最后的加号是一个Quantifier ——匹配一次和无限次,尽可能多次

You can test it here你可以在这里测试

Your description can be broken down into the regex:您的描述可以分解为正则表达式:

^(?:\??[a-zA-Z0-9])+\??$

You say characters and your description shows letters and numbers only, but it's possible \\w (word characters) may be used instead - this includes underscore您说的是字符,而您的描述仅显示字母和数字,但可以使用\\w (单词字符)来代替 - 这包括下划线

It's between ^ and $ meaning the whole field must match (no partial matches, although if you want those you can remove this. The + means there must be at least one match (so empty string won't match). The capturing group ( (\\??[a-zA-Z0-9]) ) says I must either see a question mark followed by letters or just letters repeating many times, and the final question mark allows the string to end with a single question mark.它在^$之间意味着整个字段必须匹配(没有部分匹配,但如果你想要那些你可以删除它。 +意味着必须至少有一个匹配(所以空字符串不会匹配)。捕获组( (\\??[a-zA-Z0-9]) ) 说我必须看到一个问号后跟字母或只是字母重复多次,最后一个问号允许字符串以单个问号结尾。

You probably don't want capturing groups here, so we can start that with ?: to prevent capture leading to:你可能不想在这里捕获组,所以我们可以从?:开始,以防止捕获导致:

^(?:\??[a-zA-Z0-9])+\??$

Matches火柴

test  
?test  
?test?test  
test?

Doesn't match不匹配

??test
???test
test??test
test??
<empty string>
?

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

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