Python就像sed一样使用正则表达式

时间:2012-04-20 17:54:26

标签: python regex sed

让我说,我有:

string= '{'id': '1'}'

现在使用像Perl / sed这样的字符串我想得到

string=id

(在Perl中它看起来像string = ~s / {\'([a-zA-Z0-9] )\'。 $)/ \ 1 /)

你能不能给我一点见解如何在python中做到这一点?我希望正则表达式的语法类似,但我不确定python语法和我应该使用什么导入,我是Python初学者:)非常感谢你: - )

2 个答案:

答案 0 :(得分:1)

在Python中,您可以使用re模块进行正则表达式操作。我稍微修改了你的正则表达式,但通常,这是在python中正则表达式替换的方法:

>>> import re
>>> s = "{'id': '1'}"
>>> re.sub(r"{'([^\']*)'.*$", r'\1', string)
'id'

sub()函数首先接受正则表达式,然后接受替换,最后接受字符串。 re模块的文档包含更多信息: http://docs.python.org/library/re.html

作为参数传递的字符串的r前缀基本上告诉Python将它们视为“原始”字符串,其中大多数反斜杠转义序列都不会被解释。

答案 1 :(得分:0)

首先,我同意@PenguinCoder:因为这是有效的JSON,所以你应该考虑使用Python支持来处理JSON。

我去了Google并输入了关键字:Python regular expressions

以下是前两首点击:

http://docs.python.org/library/re.html

http://docs.python.org/howto/regex.html

如果您阅读它们,您将找到答案。

这是工作代码:

import re

s = '''string= "{'id': '1'}"'''

pat = re.compile(r"\s*([^=]+)\s*=[\s'\"]*{\s*'([^']+)'")

m = pat.match(s)

if m is not None:
    id = m.group(1)
    name = m.group(2)
    result = "%s=%s" % (id, name)
    # note: could also do this: result = "%s=%s" % m.groups()