以Python组的形式获取正则表达式结果
我试图找到表达式,但我希望值作为一个整体,而不是单独的值:以Python组的形式获取正则表达式结果,python,regex,Python,Regex,我试图找到表达式,但我希望值作为一个整体,而不是单独的值: test = "code.coding = 'DS-2002433E172062D';" find = re.compile('[A-Z,\d]') hey= re.findall(find,str(test)) print hey response = ['D, 'S', '2', '0', '0', '2', '6', '6', '8', '0', '3', 'E', '1', '7', '2', '0', '6', '2', 'D
test = "code.coding = 'DS-2002433E172062D';"
find = re.compile('[A-Z,\d]')
hey= re.findall(find,str(test))
print hey
response = ['D, 'S', '2', '0', '0', '2', '6', '6', '8', '0', '3', 'E', '1', '7', '2', '0', '6', '2', 'D']
但是,我希望它作为DS-2002433E172062D您当前的正则表达式,
[A-Z,\d]
匹配A-Z范围内的单个字符或数字。您希望在匹配中捕获所需的全部字符串。试用:
输出:
['DS-2002433E172062D']
['DS-2002433E172062D']
说明:
[ // start of single character match
a-zA-Z0-9 // matches any letter or digit
]{2} // matches 2 times
- // matches the - character
[ // start of single character match
a-zA-Z0-9 // matches any letter or digit
]+ // matches between 1 and unlimited times (greedy)
作为对前面答案的改进,我经常使用如下效用函数: Python函数: 像这样使用: 产出:
正则表达式需要
()
才能成为一个组:
你有:
'[A-Z,\d]'
这意味着:范围A-Z
或“,”(逗号)或模式\d
(数字)中的任何字母作为单个匹配项。。。这分别产生了所有匹配项(并且巧妙地省略了需要包含的破折号)
对于相同类型匹配的组,请尝试:
'([A-Z,\d]+)+'
这意味着:范围A-Z
或“,”(逗号)或模式\d
(数字)中的任何字母每组匹配一次或多次,并且一组或多组预输入。。。这将生成所有的匹配项作为组(并且显然省略了需要包含([A-Z,\d]+)+
)的破折号)
要点:使用()
(括号)表示正则表达式中的组
最后,在测试regex时,在掌握模式的窍门之前,使用类似的调试器可能会有所帮助
编辑:
抱歉,我错过了关于您希望如何使用DS-2002433E172062D的部分
要获得使用组的结果,请尝试:
'([-A-Z,\d]+)+'
这意味着:a-
(破折号)或范围a-Z
或,
(逗号)或模式\d
(数字)中的任何字母,每个组匹配一次或多次,并且一个或多个组预输入。。。这将生成所有匹配项作为组。请注意,-
(破折号)必须在大多数(所有?)正则表达式的任何范围之前,根据我的经验,最好将破折号作为模式的开始
希望这对您有所帮助您非常接近,只需更改您的正则表达式模式:
pattern=r'[A-Z,\d]'
到
完整代码:
import re
test = "code.coding = 'DS-2002433E172062D';"
pattern=r'[A-Z,\d-]+'
print(re.findall(pattern,test))
输出:
'([-A-Z,\d]+)+'
pattern=r'[A-Z,\d]'
pattern=r'[A-Z,\d-]+'
import re
test = "code.coding = 'DS-2002433E172062D';"
pattern=r'[A-Z,\d-]+'
print(re.findall(pattern,test))
['DS-2002433E172062D']