CamelCase to Spaced Sentence Case正则表达式

时间:2015-10-15 21:19:25

标签: python regex camelcasing

几乎就在那里,但我发现我的正则表达式上有几个漏洞可以将CamelCase变成Spaced Sentence Case。它在大多数情况下表现良好(双关语),但它会挂在第一个带连字符的单词上。我无法弄清楚原因。

import re

# ---------------------------------------------------------
def camelCaseToSpacedTitleCase(u):
  # add spaces
  regex = re.sub("(.)([A-Z][a-z-]+)", r"\1 \2", u)

  # make title case
  regex = re.sub("([a-z0-9])([A-Z])", r"\1 \2", regex)

  # keep CAPITALISED words
  regex = re.sub("(^|\s)(\S)", r"\1" + r"\2".upper(), regex)

  # keep Mc and Mac
  regex = re.sub("(Mc|Mac)(\s)", r"\1", regex)

  # keep digits
  regex = re.sub("([a-z]+)([0-9]+\s)", r"\1 \2", regex)

  # keep I or A
  regex = re.sub("(\sA|\sI)([A-Z])([a-z]*)", r"\1 \2\3", regex)

  # remove double whitespaces
  regex = re.sub("\s{2,32}", r" ", regex)

  return regex


test1 = "TheAmazingSpider-Man"
test2 = "WeAreSexBob-Omb"
test3 = "SR-128  SomethingSomething"
test4 = "Ex-Voto - Monitor"
test5 = "FergusMcNeilEyeContact"
test6 = "It'sABanana"
test7 = "HouseOf1000Zombies!"

print (camelCaseToSpacedTitleCase(test1))
print (camelCaseToSpacedTitleCase(test2))
print (camelCaseToSpacedTitleCase(test3))
print (camelCaseToSpacedTitleCase(test4))
print (camelCaseToSpacedTitleCase(test5))
print (camelCaseToSpacedTitleCase(test6))
print (camelCaseToSpacedTitleCase(test7))

我希望看到

"The Amazing Spider-Man" 
"We Are Sex Bob-Omb"
"SR-128 Something Something"
"Ex-Voto - Monitor"
"Fergus McNeil Eye Contact"
"It's A Banana"
"House Of 1000 Zombies!"

出于上述原因,我想避免使用.titlecase()

1 个答案:

答案 0 :(得分:2)

这种处理方式可能很棘手。我认为您第一次添加空格时,您遇到的问题就出现了。不要在任何驼峰案例拆分中添加空格,只有在拆分前不使用连字符时才应用。

# Replace: regex = re.sub("(.)([A-Z][a-z-]+)", r"\1 \2", u)
regex = re.sub("([^-])([A-Z][a-z-]+)", r"\1 \2", u)

给出以下结果......

# The Amazing Spider-Man
# We Are Sex Bob-Omb
# SR-128 Something Something
# Ex-Voto - Monitor
# Fergus McNeil Eye Contact
# It's A Banana
# House Of 1000 Zombies!