我试图让正则表达式起作用,但没有成功。我已经能够将表达式限制为 10 位字母数字:
(^[a-zA-Z0-9]{10}+$)
但是我也试图让它允许 $ 字符在任何位置只有 1 个匹配。
对于诸如pQp3b8ar$8
或k7DdRoB$5W
之类的东西来说,它应该是正确的。
最佳答案
三个一般注意事项:
^[a-zA-Z0-9$]{10}$
- the parentheses are not necessary
{10}+
does not make much sense, drop the plus (there's no need for a possessive quantifier on a fixed count)- if you want to allow a dollar sign, just add it to the character class
To allow a dollar sign only once, you can use an extended version of the above:
^(?=[^$]*\$[^$]*$)[a-zA-Z0-9$]{10}$
The (?=[^$]*\$[^$]*$)
is a look-ahead that reads
(?= # start look-ahead
[^$]* # any number of non-dollar signs
\$ # a dollar sign
[^$]* # any number of non-dollar signs
$ # the end of the string
) # end of look-ahead
它允许字符串中的任何字符出现一次,但美元除外。
另一种变体是使用两个前瞻,如下所示:
^(?=[^$]*\$[^$]*$)(?=[a-zA-Z0-9$]{10}$).*
这里您可以使用 .*
来匹配字符串的其余部分,因为这两个条件是由前瞻检查的。此方法对于 password complexity checks 很有用。 ,例如。
关于regex - 无法找出特定的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437906/