大字符串格式/替换的Regex替代方案
我有一个非常大的键值对字符串(旧字符串),其格式如下:大字符串格式/替换的Regex替代方案,regex,string,python-3.x,replace,Regex,String,Python 3.x,Replace,我有一个非常大的键值对字符串(旧字符串),其格式如下: "visitorid"="gh43k9sk-gj49-92ks-jgjs-j2ks-j29slgj952ks", "customer_name"="larry", "customer_state"="alabama",..."visitorid"="..." 这个字符串非常大,因为它最多可以容纳30000个客户。我用它来写一个文件,上传到一个在线分段工具,它需要以这种方式格式化,只需修改一次——主键(visitorid)需要用制表符分隔,
"visitorid"="gh43k9sk-gj49-92ks-jgjs-j2ks-j29slgj952ks", "customer_name"="larry", "customer_state"="alabama",..."visitorid"="..."
这个字符串非常大,因为它最多可以容纳30000个客户。我用它来写一个文件,上传到一个在线分段工具,它需要以这种方式格式化,只需修改一次——主键(visitorid)需要用制表符分隔,而不是用引号括起来。最终结果需要如下所示(注意,4个空格是一个选项卡):
我编写了下面的函数,可以做到这一点,但我注意到脚本的这一部分运行得最慢(我假设是因为regex通常很慢)
有没有一种方法可以在没有正则表达式的情况下加快速度?这种方法是错误的:匹配符合正则表达式的所有匹配项,然后用修改后的匹配项替换所有匹配项。您可以简单地使用
re.sub
查找所有不重叠的匹配项,并用您需要的内容替换它们
见此:
我在正则表达式的开头添加了“\w+”=
,以匹配GUID值的键来删除它,并将末尾的,
替换为(?:,|$)
,以匹配,
或字符串的结尾(也处理键值是字符串中最后一个键值的情况)并将需要保留的部分用括号括起来
替换内容是对捕获组#1的反向引用和一个制表符。如果有任何问题,请告诉我。
gh43k9sk-gj49-92ks-jgjs-j2ks-j29slgj952ks "customer_name"="larry", "customer_state"="alabama",...ABC3k9sk-gj49-92ks-dgjs-j2ks-j29slgj9bbbb
def getGUIDS(old_string):
'''
Finds guids in the string and formats it as PK for syncfile
@param old_string the string created from the nested dict
@return old_string_fmt the formatted version
'''
print ('getting ids')
ids = re.findall('("\w{8}-\w{4}-\w{4}-\w{4}-\w{12}",)', cat_string) #looks for GUID based on regex
for element in ids:
new_str = str(element.strip('"').strip('"').strip(",").strip('"') + ('\t'))
old_string_fmt = old_string.replace(element, new_str)
return old_string_fmt
import re
def getGUIDS(old_string):
'''
Finds guids in the string and formats it as PK for syncfile
@param old_string the string created from the nested dict
@return old_string_fmt the formatted version
'''
print ('getting ids')
return re.sub(r'"\w+"="(\w{8}(?:-\w{4}){4}-\w{12})"(?:,|$)', '\\1\t', old_string) #looks for GUID based on regex
s='"visitorid"="gh43k9sk-gj49-92ks-jgjs-j2ks-j29slgj952ks", "customer_name"="larry", "customer_state"="alabama",..."visitorid"="..."'
print(getGUIDS(s))
# => getting ids
# => gh43k9sk-gj49-92ks-jgjs-j2ks-j29slgj952ks "customer_name"="larry", "customer_state"="alabama",..."visitorid"="..."