繁体   English   中英

为什么在使用\\ d * regex表示法拆分字符串时会得到一个字符数组?

[英]Why do I get an array of chars when splitting a string using \d* regex notation?

例如,我的字符串是:

 "this8is8my8string"

以下是两个不同的结果:

2.1.0 :084 > str.split(%r{\d})
 => ["this", "is", "my", "string"] 
2.1.0 :085 > str.split(%r{\d*})
 => ["t", "h", "i", "s", "i", "s", "m", "y", "s", "t", "r", "i", "n", "g"]

我不太明白为什么字符串被字符拆分,如果它们之间没有数字。 有人可以澄清第二版中发生了什么吗?

因为*表示“零或更多”,并且:

"this8is8my8string"
 ^^ there's 0 or more digits between the t and the h
  ^^ there's 0 or more digits between the h and the i
   ^^ there's 0 or more digits between the i and the s
    ^^ well... you get the point

你可能正在寻找+ \\d+表示“一个或多个数字”。

另外,在一个稍微相关的主题上:Ruby中的regexen通常被视为正则表达式文字,例如/\\d*/ ,而不是%r格式。 当我读到你的问题时,这实际上让我失望了; 看起来很奇怪。 我建议使用/.../ literal格式使大多数Rubyist的代码更容易阅读。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM