Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.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,输出为: import re caps = "bottle caps/ soda caps/ pop caps" regex = re.findall(r"\w[1-6]", caps) print(regex) 但是如果我这样做 [] 输出为: import re caps = "bottle caps/ soda caps/ pop caps" regex = re.findall(r"\w[1-6]*", caps) 如何使其输出: ['b', 'o', 't', 't', '

输出为:

import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]", caps)

print(regex)
但是如果我这样做

[]
输出为:

import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]*", caps)
如何使其输出:

['b', 'o', 't', 't', 'l', 'e', 'c', 'a', 'p', 's', 's', 'o', 'd', 'a', 'c', 'a', 'p', 's', 'p', 'o', 'p', 'c', 'a', 'p', 's']
我知道你们会建议使用
.split
,但我想更了解正则表达式

我也试过这个:

["bottle caps", "soda caps, "pop caps"]
输出:

import re
caps = "bottle caps/ soda caps/ pop caps"

regex = re.findall(r"\w[1-6]?\s*\w[1-3]*", caps)

print(regex)

发生了什么?

您似乎把
{1,6}
[1-6]
混淆了,前者表示“先前的模式重复了1到6次”,后者表示“范围
1
6
中的任何字符”

那么,你有什么:

['bo', 'tt', 'le', 'ca', 'ps', 'so', 'da', 'ca', 'ps', 'po', 'p c', 'ap']

…将匹配一个单词字符,后跟1-6之间的数字


*
放在末尾只意味着该数字模式的0或更多,这意味着任何单词字符后跟0或更多1-6的数字


但如果使用正确的语法,您将得到您想要的:

\w[1-6]

您可以使用
r”(\w+[\s\b]+\w+)
,意思是:
\w+
=一个单词<代码>[\s\b]=空格或单词边界:

\w{1,6}


您将自己与实际定义的字符类混淆,
[1-6]
将匹配范围
1
6
之间的单个字符。您可能是指
{1,6}
,它将在
1
6
之间匹配前面的正则表达式标记,称为范围运算符

在第二次尝试中,通过在字符类
[1-6]
前面加上
*
操作符,您告诉正则表达式引擎匹配前面的标记“零次或更多次”,这将导致每个单词字符单独匹配,因为您的字符串中没有数字字符

相反,您可以简单地将正则表达式编写为:

(\w+[\s\b]+\w+)
@nu11p01n73R我知道你们会建议使用.split,但我想更多地了解正则表达式
re.findall(r'\w+caps',caps)
->
[“瓶盖”、“汽水盖”、“波普瓶盖”]
(\w+[\s\b]+\w+)
>>> re.findall(r"\w+ \w+", caps)
['bottle caps', 'soda caps', 'pop caps']