Python:使用正则表达式将驼峰式大小写转换为空格分隔并考虑首字母缩略词 [英] Python: convert camel case to space delimited using RegEx and taking Acronyms into account

查看:42
本文介绍了Python:使用正则表达式将驼峰式大小写转换为空格分隔并考虑首字母缩略词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 将驼峰式大小写转换为空格分隔值.例如:

I am trying to convert camel case to space separated values using python. For example:

divLineColor -> div 线条颜色

divLineColor -> div Line Color

这一行成功了:

label = re.sub("([A-Z])"," \g<0>",label)

我遇到的问题是像 simpleBigURL 这样的东西,他们应该这样做:

The problem I am having is with things like simpleBigURL they should do this:

simpleBigURL -> 简单的大 URL

simpleBigURL -> simple Big URL

我不完全确定如何得到这个结果.帮助!

I am not entirely sure how to get this result. Help!

这是我尝试过的一件事:

This is one thing that I tried:

label = re.sub("([a-z])([A-Z])","\g<0> \g<1>",label)

但这会产生奇怪的结果,例如:

But this produces weird results like:

divLineColor -> divL vineC 颜色

divLineColor -> divL vineC eolor

我还认为使用 (?!...) 可以工作,但我没有任何运气.

I was also thinking that using the (?!...) could work but I have not had any luck.

推荐答案

\g<0> 引用整个模式的匹配字符串,而 \g<1>引用第一个子模式的匹配字符串 ((...)).所以你应该使用 \g<1>\g<2> 代替:

\g<0> references the matched string of the whole pattern while \g<1> refereces the matched string of the first subpattern ((…)). So you should use \g<1> and \g<2> instead:

label = re.sub("([a-z])([A-Z])","\g<1> \g<2>",label)

这篇关于Python:使用正则表达式将驼峰式大小写转换为空格分隔并考虑首字母缩略词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆