解释这个特定的正则表达式

0 投票
3 回答
577 浏览
提问于 2025-04-15 12:52

我之前写了一个正则表达式,但现在不记得它的意思了。对我来说,这就像是一种只能写不能读的语言 :)

这是那个正则表达式:

"(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"

我想知道,用简单的英语来说,它是什么意思。

3 个回答

2

RegexBuddy 提到以下内容 (!?!):

(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$

Options: ^ and $ match at line breaks

Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!^[0-9]*$)»
   Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
   Match a single character in the range between “0” and “9” «[0-9]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
   Assert position at the end of a line (at the end of the string or before a line break character) «$»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!^[a-zA-Z]*$)»
   Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
   Match a single character present in the list below «[a-zA-Z]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
      A character in the range between “a” and “z” «a-z»
      A character in the range between “A” and “Z” «A-Z»
   Assert position at the end of a line (at the end of the string or before a line break character) «$»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match the regular expression below and capture its match into backreference number 1 «([a-zA-Z0-9]{8,10})»
   Match a single character present in the list below «[a-zA-Z0-9]{8,10}»
      Between 8 and 10 times, as many times as possible, giving back as needed (greedy) «{8,10}»
      A character in the range between “a” and “z” «a-z»
      A character in the range between “A” and “Z” «A-Z»
      A character in the range between “0” and “9” «0-9»
Assert position at the end of a line (at the end of the string or before a line break character) «$»  
4

Perl(还有Python)对(?!...)部分的解释是:

这是一个零宽度的负向前瞻断言。举个例子,/foo(?!bar)/会匹配任何出现的'foo',前面不跟着'bar'。不过要注意,前瞻和后顾是不同的。你不能用这个来做后顾。

这意味着,

(?!^[0-9]*$)

意思是:如果字符串只包含数字,就不匹配。^表示行/字符串的开始,$表示行/字符串的结束)其他的也是类似的。

你的正则表达式会匹配任何同时包含数字字母的字符串,但不能只包含其中一个。

祝好,

更新:为了将来更好地定制你的正则表达式,可以看看(?#...)这个模式。它允许你在正则表达式中嵌入注释。另外还有一个修饰符re.X,不过我不太喜欢这个,选择权在你。

5
(?!^[0-9]*$)
(?!^[a-zA-Z]*$)
^([a-zA-Z0-9]{8,10})$

不只匹配数字,

不只匹配字母,

匹配字母和数字,长度在8到10个字符之间。

撰写回答