Python 具有常量字符串的特定短语的正则表达式
使用正则表达式查找python字符串中的特定短语的大小写 我目前运行一个for循环,以按照类似的格式运行一长串字符串。请参阅下面的代码: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变量是一个字符
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)