Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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 如果特定字符出现特定次数,则使用正则表达式进行匹配_Python_Regex - Fatal编程技术网

Python 如果特定字符出现特定次数,则使用正则表达式进行匹配

Python 如果特定字符出现特定次数,则使用正则表达式进行匹配,python,regex,Python,Regex,我正在尝试使用正则表达式来检查字符串str是否至少包含两个数字,并且正好包含以下任意符号中的两个:“!”、“@”、“#”、“$”、“%”、“&”和“*” 似乎正在发生的是,我只在它们连续出现而不是全部出现时才匹配。我该如何解决这个问题 str = 'a1b2c$3d#4e!f@ghi0' sym = '[!@#$%&*]{2}' num = '[0-9]{2,}' for char in str: if re.search(sym, str): if re.s

我正在尝试使用正则表达式来检查字符串str是否至少包含两个数字,并且正好包含以下任意符号中的两个:“!”、“@”、“#”、“$”、“%”、“&”和“*”

似乎正在发生的是,我只在它们连续出现而不是全部出现时才匹配。我该如何解决这个问题

str = 'a1b2c$3d#4e!f@ghi0'

sym = '[!@#$%&*]{2}'
num = '[0-9]{2,}'

for char in str:
    if re.search(sym, str):
        if re.search(num, str):
            print('match!')
        else:
            print('no matches!')

如果您想使用2种模式,则不必循环检查每个字符。在
sym
中,您可以检查字符串是否正好包含列出的两个字符

num
中,您至少可以匹配两位数字

import re

str = 'test$test$test123'

sym = r'^[^!@#$%&*\r\n]*[!@#$%&*][^!@#$%&*\r\n]*[!@#$%&*][^!@#$%&*\r\n]*\Z'
num = r'^[^\d\r\n]*\d[^\d\r\n]*\d'

if re.search(sym, str) and re.search(num, str):
    print('match!')
else:
    print('no matches!')

您还可以将单个模式与re.match一起使用

^(?=[^\d\r\n]*\d[^\d\r\n]*\d)[^!@#$%&*\r\n]*[!@#$%&*][^!@#$%&*\r\n]*[!@#$%&*][^!@#$%&*\r\n]*\Z
解释

  • ^
    字符串的开头
  • (?=[^\d\r\n]*\d[^\d\r\n]*\d)
    正向前瞻,断言2个数字
  • [^!@$%&*\r\n]*[!@$%&*][^!@$%&*\r\n]*[!@$%&*\r\n]*[!@$%%&*][^!@$%&*\r\n]*
    匹配列出的任何字符中的两个字符
  • \Z
    字符串结尾
|


在不使用正则表达式的情况下,一个选项是计算数字和特殊字符的出现次数:

s = 'test$test$test123'
specialChars = "!@#$%&*"
num = 0
sym = 0

for char in s:
    if char.isdigit():
        num += 1
    if char in specialChars:
        sym += 1

if num > 1 and sym == 2:
    print("Match")

您可以使用类似于
^(?=.*([!@$%&*]).\1)(?=\D*\D*\D.+
尝试使用sym=“^(.*?[!@$%&*]){2}$”和num=“^(.\\\\\\ D.?{2,}$”;谢谢你的输入,我仍然对正则表达式中的元字符很熟悉。
s = 'test$test$test123'
specialChars = "!@#$%&*"
num = 0
sym = 0

for char in s:
    if char.isdigit():
        num += 1
    if char in specialChars:
        sym += 1

if num > 1 and sym == 2:
    print("Match")