为什么下面的第二个split
返回标点符号?为什么在正则表达式中使用括号会改变输出?
str = "This is a test string. Let's split it."
str.split(/\. /)
# =>["This is a test string", "Let's split it."]
str.split(/(\. )/)
# =>["This is a test string", ". ", "Let's split it."]
发布于 2015-06-19 19:29:20
因为第二个代码使用包含组的regex。来自String#split
如果模式是
Regexp
,则str
被划分为模式匹配的位置。每当模式匹配零长度字符串时,str就被拆分为单个字符。如果模式包含组,则相应的匹配也将在数组中返回.。
https://stackoverflow.com/questions/30949933
复制