regex - 无法找出特定的正则表达式

标签 regex

我试图让正则表达式起作用,但没有成功。我已经能够将表达式限制为 10 位字母数字:

(^[a-zA-Z0-9]{10}+$)

但是我也试图让它允许 $ 字符在任何位置只有 1 个匹配。

对于诸如pQp3b8ar$8k7DdRoB$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/

相关文章:

java - 需要正则表达式来验证自定义输入

php - MySQL 使用 RegEx 更新/选择列

java - Printf 和 regex 用于格式化 Java 输出

Javascript - 使用变量 RegExp 来匹配数据数组中的多个关键字

javascript - 突出显示jquery中的当前页面

regex - 如何在 perl 中拆分和保留拆分标准

javascript - JavaScript 正则表达式中的 type=number 和 type=text 有什么区别?

javascript - 正则表达式验证 AngularJs

Python用正则表达式匹配实数/ float

javascript - 用多个分隔符拆分字符串,保留它们并在双引号中忽略它们