Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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 Regexp子函数_Python_Regex - Fatal编程技术网

Python Regexp子函数

Python Regexp子函数,python,regex,Python,Regex,我试图在python中使用子函数,但无法使其工作。到目前为止我有 content = '**hello**' content = re.sub('**(.*)**', '<i>(.*)</i>', content) 取而代之 <i>hello</i> 你好 有什么想法吗?您需要转义*字符,并使用替换功能: content = '**hello**' content = re.sub('\*\*(.*)\*\*', lambda p : '&l

我试图在python中使用子函数,但无法使其工作。到目前为止我有

content = '**hello**'
content = re.sub('**(.*)**', '<i>(.*)</i>', content)
取而代之

<i>hello</i>
你好
有什么想法吗?

您需要转义
*
字符,并使用替换功能:

content = '**hello**'
content = re.sub('\*\*(.*)\*\*', lambda p : '<i>%s</i>' % p.group(1), content)
content='**hello**
content=re.sub('\*\*(.*)\*\*',lambda p:'%s'%p.group(1),content)
或者,您可以使用命名组

content = re.sub('\*\*(?P<name>.*)\*\*', '<i>\g<name></i>', '**hello**')
content = re.sub('\*\*(.*)\*\*', '<i>\\1</i>', '**hello**')
content=re.sub('\*\*(?P.*)\*\*'、'\g'、'**hello**'))
或者,作为更好的选择,编号组

content = re.sub('\*\*(?P<name>.*)\*\*', '<i>\g<name></i>', '**hello**')
content = re.sub('\*\*(.*)\*\*', '<i>\\1</i>', '**hello**')
content=re.sub(“\*\*(.*)\*\*”、“\\1”、“你好**”)

谢谢,但它将替换为(.*),而不是hello。这并不能给出所需的答案。谢谢,这很好,但如果我有hello,我只想匹配它,如果是hello,我将如何实现它?而不是替换函数,您可以使用
r'\1'
**foo**bar**