Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用ruby拆分这个字符串?_Ruby - Fatal编程技术网

如何用ruby拆分这个字符串?

如何用ruby拆分这个字符串?,ruby,Ruby,我想从最后一个下划线中拆分字符串。字符串如下所示: "abc_123_identifier_12345" 输出: ["abc_123_identifier", "12345"] 请告诉我你是否有同样的好主意。提前谢谢 试试这个: "abc_123_identifier_12345".split(/_(\d+)$/) #=> ["abc_123_identifier", "12345"] 对我来说,看起来更像是模式匹配任务,而不是拆分任务: [1] pry(main)> /^(.

我想从最后一个下划线中拆分字符串。字符串如下所示:

"abc_123_identifier_12345"
输出:

["abc_123_identifier", "12345"]
请告诉我你是否有同样的好主意。提前谢谢

试试这个:

"abc_123_identifier_12345".split(/_(\d+)$/)
#=> ["abc_123_identifier", "12345"]

对我来说,看起来更像是模式匹配任务,而不是拆分任务:

[1] pry(main)> /^(.*)_(\d*)$/.match("abc_123_identifier_12345").captures
=> ["abc_123_identifier", "12345"]
控制台中的输出

[22] pry > a = "abc_123_identifier_12345"
=> "abc_123_identifier_12345"
[23] pry > a.rpartition('_') - ['_']
=> ["abc_123_identifier", "12345"]

您想如何分割它?在第三条下划线上?最后一个下划线?最后一个非数字字符?核心团队确实需要在第三个下划线上添加
String#rsplit
@Yule abc#u 123_671_123标识符_671_123应该返回“671_123”?@pangpang,所以这是最后一个,而不是第三个…是的,很好。我真的应该让正则表达式成为我的“go-to”解决方案…它可能是正确的答案,也可能不是正确的答案,这取决于OP真正想要什么这就是我想要的,谢谢!
[22] pry > a = "abc_123_identifier_12345"
=> "abc_123_identifier_12345"
[23] pry > a.rpartition('_') - ['_']
=> ["abc_123_identifier", "12345"]