正则表达式,在Python中使用包含空格的表达式

时间:2018-03-18 16:28:10

标签: python

我在阅读文档后生成了这个表达式:

li

意在识别这种模式:

  

['1','11','111'] ['cpp','h']'utf-8'500

我试图在Python 3.5.4中使用它:

(\['[^']+'(?:,\s*'[^']+'){0,}\]) (\[(?:'[^']+')(?:,\s*'[^']+'){0,}\]) ('[^']+') ([1-9][0-9]*)

我能认出这个例子:

  

['1','11','111'] ['cpp','h']'utf-8'500

但是在尝试识别时:

  

['1','11','111'] ['cpp','h']'utf-8'500

或者这个:

  

['1','1 1','1 11'] ['cp p','h']'utf-8'500

只要在import re import sys x = sys.argv[1:] args = re.match(u"(\['[^']+'(?:,\s*'[^']+'){0,}\]) (\['[^']+'(?:,\s*'[^']+'){0,}\]) ('[^']+') ([1-9][0-9]*)", ' '.join(x)) (')之间或(')(',)之间表示空格,python中的

就会失败。

但在这个site上,正则表达式就像一个魅力。

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:1)

我是愚蠢的,noob的错误,在python中的第一个项目。

我完全忘记了在cmd中,只要包含空格,我就应该使用'“'来包含文本。

错误的方式:

  

python re-encoder.py ['1','11','11 1'] ['cpp','h']'utf-8'500

正确方式:

  

python re-encoder.py“['1','1 1','11 1']”“['cpp','h']”'utf-8'500

在cmd中调用脚本

答案 1 :(得分:1)

将参数作为字符串传递将起作用。 为什么不这样做?

import re
import sys
x = sys.argv[1:]
args = re.match(u"(\['[^']+'(?:,\s*'[^']+'){0,}\]) (\['[^']+'(?:,\s*'[^']+'){0,}\]) ('[^']+') ([1-9][0-9]*)",
                ' '.join(x))

g = args.groups()
print(g[0])
print(g[1])
print(g[2])
print(g[3])

试试这个。

$ python re-encoder.py "['1', '11', '111'] ['cpp', 'h'] 'utf-8' 500"

结果

['1', '11', '111']
['cpp', 'h']
'utf-8'
500