1

很长一段时间以来,我一直能够通过正则表达式跌跌撞撞,但是唉,我无法帮助有需要的朋友。

我的“朋友”正在尝试匹配文本文件中符合以下条件的所有行:

  1. 只有 7 到 10 位数字(0123456 或 0123456789)
  2. 只有 7 到 10 位数字,然后是破折号,然后是另外两位数字(0123456-01 或 0123456789-01)
  3. 匹配上述任何一项,除非代码/代码或密码/密码在要匹配的数字之前(例如“访问代码:16434629”或“密码 5253443-12”)
  4. 编辑:只需要匹配的数字,没有别的。

这是我见过的“他”给我的最讨厌的正则表达式:

^(?=.*?[^=/%:]\b\d{7,10}((\d?\d?)|(-\d\d))?\b)((?!Passcode|passcode|Code|code).)*$

...

问题:有没有办法使用简短的正则表达式来查找符合上述条件的所有行?

假设 PCRE。我的朋友提前谢谢你。;-)

顺便说一句 - 我无法在 stackoverflow.com 或 superuser.com 中找到可以准确回答此问题的任何其他问题。

编辑:我正在使用 Kodos Python Regex Debugger 来验证和测试正则表达式。

4

2 回答 2

4
(?<!(?:[Pp]asscode|[Cc]ode).*)[0-9]{7,10}(?:-[0-9]{2})?

评论版本:

(?<!                 # Begin zero-width negative lookbehind. (Makes sure the following pattern can't match before this position)
(?:                  # Begin non-matching group
[Pp]asscode          # Either Passcode or passcode
|                    # OR
[Cc]ode              # Either Code or code
)                    # End non-matching group
.*                   # Any characters
)                    # End lookbehind
[0-9]{7,10}          # 7 to 10 digits
(?:                  # Begin non-matching group
-[0-9]{2}            # dash followed by 2 digits
)                    # End non-matching group
?                    # Make last group optional

编辑:评论讨论后的最终版本 -

/^(?!\D*(?:[Pp]asscode|[Cc]ode))\D*([0-9]{7,10}(?:-[0-9]{2})?)/

(导致第一个捕获缓冲区)

于 2009-12-23T20:53:01.260 回答
1

你可以通过一个讨厌的正则表达式来获得帮助......

...或者您可以使用两个简单的正则表达式。一种匹配您想要的,另一种过滤您想要的。更简单,更易读。

Which one would you like to read?

$foo =~ /(?<!(?:[Pp]asscode|[Cc]ode).*)[0-9]{7,10}(?:-[0-9]{2})?/

or

$foo =~ /\d{7,10}(-\d{2})?/ and $foo !~ /(access |pass)code/i;

Edit: case-insensitivity.

于 2009-12-23T21:02:21.350 回答