我正在寻找一个Regex来匹配一个字符串,该字符串应该:
978-或979-前缀开始x)的序列结尾。注:连字符可以用空格替换(连贯),也可以完全不存在。
比赛:
不匹配:
978 0 30909169 5我目前的观点是,多亏了以前的问题的答案,我应该能够进一步简化:/^((97(8|9))*\d{9}|(97(8|9)-)*(?=.{11}-)(?:\d+-){3}|(97(8|9) )*(?=.{11} )(?:\d+ ){3})[\dx]$/i
发布于 2021-01-27 21:02:09
你可以尝试:
^(?![- ])(?:(?:97[89])?([- ]?)(?=(?:\d\1?){9}\1[\dxX]$)(?:\d+\1){3}[\dxX]|(?=.{11}([- ])[\dxX]$)(?:\d+\2){3}[\dxX])请参阅在线演示
^ -启动字符串锚.(?![- ]) -负向前看,以防止前导连字符或空格。(?: -开放非捕获组:(?: -开放非捕获组:97[89] -匹配"97“,然后是8或9。)? -关闭非捕获组,并使其可选。- `(` - Open 1st capture group:
- `[- ]?` - Optionally match an hyphen or space.
- `)` - Close 1st capture group.- `(?=` - Open positive lookahead:
- `(?:` - Open non-capture group:
- `\d\1?` - Capture a digit and optionally match what is captured in the 1st capture group.
- `){9}` - Close the non-capture group and match it nine times (to assert a position with 9 digits ahead). - `\1[\dxX]$` - Again match what is captured in the 1st capture group followed by a digit or lower- or uppercase "x" and the end string anchor.
- `)` - Close positive lookahead.- `(?:` - Open non-capture group:
- `\d+\1` - 1+ digits followed by what is captured in the 1st capture group.
- `){3}` - Close the non-capture group and match it three times.- `[\dxX]` - Match a digit, a lower- or uppercase "x".
- `|` - Or:
- `(?=` - Open positive lookahead:
- `.{11}` - Match eleven characters other than newline.
- `([- ])` - OA 2nd capture group to match either hypen or space.
- `[\dxX]$` - Match a digit, a lower- or uppercase "x" up to end string anchor.
- `)` - Close positive lookahead.- `(?:` - Open non-capture group:
- `\d+\2` - Match 1+ digits and what is captured in the 2nd capture group.
- `){3}` - Close non-capture group and match three times.- `[\dxX]$` - Match a digit, a lower- or uppercase "x".
- `)` - Close non-capture group.发布于 2021-01-27 21:06:50
此值既匹配又不匹配978 0 309 09169 5。我认为应该匹配它,因为它具有相同的前缀、10位数字和相同数量的分隔符。
另一个选项可以是使用交替|将可选前缀和10位数字或部分与分隔符匹配。
您可以使用([- ])?捕获组1中的可选空格或连字符,并使用反向引用\1来引用它,以保持分隔符的一致性。
^(?:97[89]([- ])?)?(?:\d{10}|(?=(?:\d\1?){9}\1?[xX\d]$)\d+(?:\1?\d+){2}\1?[\dxX])$解释
^起刺(?:97[89]([- ])?)?可选择匹配组1中的前缀和捕获可选连字符。(?:非捕获群\d{10}匹配10位数字|或(?=(?:\d\1?){9}\1?[xX\d]$)正向前看,断言9个数字,后面跟着一个可选的分隔符,或者是x X或一个数字,直到字符串的末尾\d+(?:\1?\d+){2}匹配1+数字并重复2次,匹配可选分隔符和1+数字。-?[\dxX]匹配可选的-和x X或数字)闭非捕获群$末端https://stackoverflow.com/questions/65925071
复制相似问题