Python,regex-如何匹配第二组,仅当第一组匹配时
输入:Python,regex-如何匹配第二组,仅当第一组匹配时,python,regex,python-3.x,Python,Regex,Python 3.x,输入: 2SASKS6SJSQSOS 2S AS KS 6S JS QS import re row = input() pattern = r"([1]?[0-9]?[JQKA]?)([SHDC])" result = '' for (first, second) in re.findall(pattern, row): if first and second: result += first + second + ' ' print(result) 预
2SASKS6SJSQSOS
2S AS KS 6S JS QS
import re
row = input()
pattern = r"([1]?[0-9]?[JQKA]?)([SHDC])"
result = ''
for (first, second) in re.findall(pattern, row):
if first and second:
result += first + second + ' '
print(result)
预期输出:
2SASKS6SJSQSOS
2S AS KS 6S JS QS
import re
row = input()
pattern = r"([1]?[0-9]?[JQKA]?)([SHDC])"
result = ''
for (first, second) in re.findall(pattern, row):
if first and second:
result += first + second + ' '
print(result)
我的代码:
2SASKS6SJSQSOS
2S AS KS 6S JS QS
import re
row = input()
pattern = r"([1]?[0-9]?[JQKA]?)([SHDC])"
result = ''
for (first, second) in re.findall(pattern, row):
if first and second:
result += first + second + ' '
print(result)
所以现在它起作用了,因为这项检查发挥了神奇的作用:
if first and second:
如果没有此支票,则返回:
2S AS KS 6S JS QS S
因为它匹配第二组
我想在正则表达式中执行此操作,而不是使用if检查,是否可能?要检查第一组是否匹配,然后再匹配第二组?您可以添加一个,以确保有一个数字或一个J
,Q
,K
或a
字母:
import re
row = '2SASKS6SJSQSOS'
pattern = r"(?=[0-9JQKA])(1?[0-9]?[JQKA]?)([SHDC])"
result = [x.group() for x in re.finditer(pattern, row)]
print(result) # => ['2S', 'AS', 'KS', '6S', 'JS', 'QS']
甚至
result = re.findall(r"(?=[0-9JQKA])1?[0-9]?[JQKA]?[SHDC]", row)
见
这是因为第二组模式与第一组中匹配的模式不重叠
见:
详细信息
-一种正向前瞻,需要一个ASCII数字,(?=[0-9JQKA])
,J
,Q
或K
,紧靠当前位置右侧a
-可选的1?
1
-可选ASCII数字[0-9]?
字符类中的可选字母:[JQKA]?
、J
、Q
或K
A
-一个[SHDC]
,S
,H
或D
字母C