我正在尝试创建一个正则表达式模式,该模式将基于许多不同的模式和约定将字符串拆分为单词数组.规则如下:
如果它正常工作,则应该如下
"theQuick--brown_fox JumpsOver___the.lazy DOG".split_words ==
["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经能够几乎到达那里,唯一的问题是它分裂了每个资本,所以"DOG".split_words是["d","o","g"]而不是["dog" ]
我还在分裂阵列上使用正则表达式和地图/过滤器的组合来获得解决方案,如果你可以告诉我如何摆脱它并仅使用正则表达式的奖励积分.
这是我到目前为止所拥有的:
class String
def split_words
split(/[_,\-, ,.]|(?=[A-Z]+)/).
map(&:downcase).
reject(&:empty?)
end
end
Run Code Online (Sandbox Code Playgroud)
从上面的测试中调用字符串时返回:
["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "d", "o", "g"]
Run Code Online (Sandbox Code Playgroud)
如何更新此方法以满足上述所有规格?
您可以稍微更改正则表达式,以便它不会分散在每个大写字母上,而是以大写字母开头的每个字母序列.这只是涉及到[a-z]+后来[A-Z]+
string = "theQuick--brown_fox JumpsOver___the.lazy DOG"
regex = /[_,\-, ,.]|(?=[A-Z]+[a-z]+)/
string.split(regex).reject(&:empty?)
# => ["the", "Quick", "brown", "fox", "Jumps", "Over", "the", "lazy", "DOG"]
Run Code Online (Sandbox Code Playgroud)