0

我做了一个函数,可以将每个字符串转换为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
4

2 回答 2

1

你能试一下吗:

def toSnakeCase(string):
    return re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', '_', j).strip('_').lower()

for i, j in enumerate(strings, 1):
    print(f'{i}. {toSnakeCase(j)}')

输出:

1. hello_world
2. hello_world
3. hello_world
4. hello_world
5. hello_world
6. hello_world
7. hello_world
8. hello_world
于 2021-09-06T20:30:00.843 回答
1

您的问题似乎只是前导和尾随,在转换_之前或之后删除它们space > _

def toSnakeCase(string):
    string = re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', ' ', string).strip().replace(' ', '_')
    return ''.join(string.lower())

用于后期剥离

string = re.sub(r'(?<=[a-z])(?=[A-Z])|[^a-zA-Z]', ' ', string).replace(' ', '_').strip("_")
于 2021-09-06T20:23:48.897 回答