我正在尝试编写一个 PCRE Regex 模式以仅匹配长度数字(8 或 9 或 12),同时保留最后 4 位未屏蔽。下面是我写的正则表达式模式。
/(?<=\D|^)(?=\d{8,12}\D|$)(\d{3})[\s,-]?\[\s,-]\K\d{4}|(?<=\D|^)(?=\d{12}|\d{9}\D|$)\d{5}/gmi
Reference Regex101 链接:https://regex101.com/r/DukWNG/1 此链接包含用于理解的工作测试用例。
现在它只匹配前 5 位数字,但对于长度 8 或 9 或 12,它应该匹配除最后 4 位数字之外的所有数字。
测试用例:
如果数字之间有“连字符”或“逗号”或“破折号”或“空格”,它也应该匹配。我被卡住了,不确定如何进行这项工作。任何帮助都会很棒。
((?:\d[-_ \.]*){4,5}|(?:\d[-_ \.]*){8})(?:\d[-_ \.]*){4}$
这种模式似乎可以胜任:
~
(?<d> [0-9] [-_ –.]* ){4} # subpattern definition / first 4 digits
(?=
\g<d>{4} (?: \g<d> (?: \g<d>{3} )? )? # allowed digit sequences
(*SKIP) (?! \g<d> ) # skip the substring when a digit remains
)
\g<d>* (?= \g<d>{4} ) # backtrack until there're 4 digits at the end
~ux
随意定义最终的分隔符应该如何准确查找。