在 RegEx 捕获组中搜索重复项?
Search for duplicates in a RegEx capturing group?
我刚刚用正则表达式匹配了一个字符串。
我想匹配包含 3 个 letter/digit 组合的字符串。
它可能包含 A、B 或 L,后跟数字 1-3。 (如果是 L,1-4)
我的问题:
当一个字母多次匹配时,我不想匹配字符串。所以A、B、L,只能出现一次。
到目前为止我的表情:
(?:[A|L|B](?(?<=L)[1-4]|[1-3])){3}
此时匹配的测试字符串:
L2B1A3
B2L1A2
A1B1L4
A1A2A3
此时不匹配的字符串:
L4B4A1 (Only L can have a digit that's 4)
L2A1B (Missing digit)
我不想匹配的字符串(现在匹配):
A2A2A3 (The A, B and L only may occur one time!)
如果我理解正确的话,这会起作用:
^(?=.*A)(?=.*B)(?=.*L)([AB][1-3]|L[1-4]){3}$
这给出了
L2B1A3 - match
B2L1A2 - match
A1B1L4 - match
A1A2A3 - no match
L4B4A1 - no match
L2A1B - no match
细分:
^ # start of string
(?=.*A) # A must occur anywhere in the string
(?=.*B) # B must occur anywhere in the string
(?=.*L) # L must occur anywhere in the string
( # begin capturing group
[AB][1-3] # A or B and 1-3
| # or
L[1-4] # L and 1-4
){3} # end group
$ # end of string
必须满足三个前瞻而主组必须匹配三次以及的事实处理了字母不能加倍的条件。
只是提供一种替代方法。
^(?!.*([A-Z]).*)(?:[AB][1-3]|L[1-4]){3}$
反向引用捕获组 1 (?!.*([A-Z]).*)
的负前瞻确保大写字母在字符串中只出现一次。
好处就是在正则表达式中加入比ABL更多的字母,正则表达式会更简洁。
我刚刚用正则表达式匹配了一个字符串。
我想匹配包含 3 个 letter/digit 组合的字符串。 它可能包含 A、B 或 L,后跟数字 1-3。 (如果是 L,1-4)
我的问题: 当一个字母多次匹配时,我不想匹配字符串。所以A、B、L,只能出现一次。
到目前为止我的表情:
(?:[A|L|B](?(?<=L)[1-4]|[1-3])){3}
此时匹配的测试字符串:
L2B1A3
B2L1A2
A1B1L4
A1A2A3
此时不匹配的字符串:
L4B4A1 (Only L can have a digit that's 4)
L2A1B (Missing digit)
我不想匹配的字符串(现在匹配):
A2A2A3 (The A, B and L only may occur one time!)
如果我理解正确的话,这会起作用:
^(?=.*A)(?=.*B)(?=.*L)([AB][1-3]|L[1-4]){3}$
这给出了
L2B1A3 - match B2L1A2 - match A1B1L4 - match A1A2A3 - no match L4B4A1 - no match L2A1B - no match
细分:
^ # start of string (?=.*A) # A must occur anywhere in the string (?=.*B) # B must occur anywhere in the string (?=.*L) # L must occur anywhere in the string ( # begin capturing group [AB][1-3] # A or B and 1-3 | # or L[1-4] # L and 1-4 ){3} # end group $ # end of string
必须满足三个前瞻而主组必须匹配三次以及的事实处理了字母不能加倍的条件。
只是提供一种替代方法。
^(?!.*([A-Z]).*)(?:[AB][1-3]|L[1-4]){3}$
反向引用捕获组 1 (?!.*([A-Z]).*)
的负前瞻确保大写字母在字符串中只出现一次。
好处就是在正则表达式中加入比ABL更多的字母,正则表达式会更简洁。