Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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_Python 3.x - Fatal编程技术网

Python 具有常量字符串的特定短语的正则表达式

Python 具有常量字符串的特定短语的正则表达式,python,regex,python-3.x,Python,Regex,Python 3.x,使用正则表达式查找python字符串中的特定短语的大小写 我目前运行一个for循环,以按照类似的格式运行一长串字符串。请参阅下面的代码: import re for x in range(len(out_lines)): test = str(out_lines[x]) out_lines[x] = re.sub(r"(name='([.*?])')", lambda m: m.group(1).lower(), test) out_lines变量是一个字符

使用正则表达式查找python字符串中的特定短语的大小写

我目前运行一个for循环,以按照类似的格式运行一长串字符串。请参阅下面的代码:

import re
for x in range(len(out_lines)):
    test = str(out_lines[x])
    out_lines[x] = re.sub(r"(name='([.*?])')", lambda m: m.group(1).lower(), test)
out_lines变量是一个字符串列表,其格式如下所示:

<column caption='Subordination' datatype='string' name='[SUBORDINATE]' role='dimension' type='nominal' />
<column caption='Issuer' datatype='string' name='[ISSUER_NAME]' role='dimension' type='nominal' />
但是整个字符串不能向下大小写,因为其他参数可能有大写字母,而这些字母需要保留


我认为我的问题是由于一个不正确的正则表达式…

您需要在regexp中转义方括号,因为方括号有特殊的含义

out_lines[x] = re.sub(r"name='\[(.*?)\]'", lambda m: "name='[" + m.group(1).lower() + "]'", test)

您不需要在整个regexp周围设置捕获组,只需要在括号内的部分周围设置捕获组。

这非常适合于对特定部分进行下套管,但是它删除了
name='[abc]'
请参见此输出:
其中预期的输出是
是否有办法将此字符串硬编码回来@BarmarI在lambda中添加了
name='[…]'
部分。
out_lines[x] = re.sub(r"name='\[(.*?)\]'", lambda m: "name='[" + m.group(1).lower() + "]'", test)