Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,regex-如何匹配第二组,仅当第一组匹配时_Python_Regex_Python 3.x - Fatal编程技术网

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)

这是因为第二组模式与第一组中匹配的模式不重叠

见:

详细信息

  • (?=[0-9JQKA])
    -一种正向前瞻,需要一个ASCII数字,
    J
    Q
    K
    a
    ,紧靠当前位置右侧
  • 1?
    -可选的
    1
  • [0-9]?
    -可选ASCII数字
  • [JQKA]?
    字符类中的可选字母:
    J
    Q
    K
    A
  • [SHDC]
    -一个
    S
    H
    D
    C
    字母

你说的第一和第二是什么意思?你能先拿什么?第二个应该是什么?你只是分成两组吗?你想分成上面的两组吗?第一组总是一个字符吗?有简单的输入和输出,我在寻找这个输入的解决方案。关于“组1是否始终只有一个字符”的问题不相关:)“是否要分成上述两组?”-是的,我想,这就是为什么“预期输出”是“预期输出”