新手问题 scan 和 split 的区别记录

pathbox · 2015年07月22日 · 最后由 sdfsd 回复于 2020年10月01日 · 3106 次阅读

最近项目里出现了大量的 scan 方法。查看了下资料,明白了它的意思。 scan 是 将满足条件(如正则表达式过滤后)的字符串返回到数组,split 是将满足条件的内容为分割点,将分割点左右两边的字符串返回到数组中。不知道这样理解是否有偏差 The output of String#split doesn't include the delimiter. Rather, everything except the delimiter would be returned in the output array, while the output of String#scan would only include what is matched by the delimiter.

A delimited string split on | returns everything surrounding the | delimiters

"a|delimited|string".split("|")

Prints: ["a", "delimited", "string"]

The same string scanninng for | only returns the matched |

"a|delimited|string".scan("|")

Prints: ["|", "|"]

Both of the above would also accept a regular expression in place of the simple string "|".

Split on everything between and including two t's

"a|delimited|string".split(/t.+t/)

Prints: ["a|delimi", "ring"]

"a|delimited|string".scan(/t.+t/)

Prints: ["ted|st"]

谢谢总结

棒棒哒!!!!!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号