我做了一个函数,可以将每个字符串转换为snakecase
但我的一些字符串会产生问题。我用re
了模块
整个代码
import re
def toSnakeCase(string, restToLower : bool = False):
string = re.sub(r'(?:(?<=[a-z])(?=[A-Z]))|[^a-zA-Z]', ' ', self.string).replace(' ', '_')
if (restToLower == True):
return ''.join(self.string.lower())
else:
return ''.join(self.string)
输入
strings = ['hello world', 'HelloWorld', '-HELLO-WORLD-', 'Hello-World', 'hello_world', '--hello.world', 'Hello-WORLD', 'helloWORLD']
# using enumerate just to see which list item creating problem
for i, j in enumerate(strings, 1):
print(f'{i}. {toSnakeCaseV1(j)}')
输出- 没有restToLower = True
1. hello_world
2. Hello_World
3. _HELLO_WORLD_
4. Hello_World
5. hello_world
6. __hello_world
7. Hello_WORLD
8. hello_WORLD
和restToLower = True
1. hello_world
2. hello_world
3. _hello_world_
4. hello_world
5. hello_world
6. __hello_world
7. hello_world
8. hello_world
如您所见,第3项和第 6项造成了问题。根据我的说法,有人知道它为什么这样做,我的正则表达式是正确的。
预期产出
1. hello_world
2. hello_world
3. hello_world
4. hello_world
5. hello_world
6. hello_world
7. hello_world
8. hello_world