Regex 返回与此匹配的数组
使用字符串:Regex 返回与此匹配的数组,regex,ruby,Regex,Ruby,使用字符串: "/create channel welcome message, hello there, any words you like..." 我需要返回一个如下所示的数组: ["channel", "welcome message, hello there, any words you like..."] 使用正则表达式 获取阵列的最佳方法是什么?在Ruby中使用捕获功能如何 /\A\/create(?[:alpha:]+)(?。+)\Z 当您使用matching=.match(
"/create channel welcome message, hello there, any words you like..."
我需要返回一个如下所示的数组:
["channel", "welcome message, hello there, any words you like..."]
使用正则表达式
获取阵列的最佳方法是什么?在Ruby中使用捕获功能如何
/\A\/create(?[:alpha:]+)(?。+)\Z
当您使用matching=.match(input)
将其与字符串匹配时,您可以使用matching[“command”]
和matching[“message”]
访问您的命令和消息。像这样:
matching = /\A\/create (?<command>[[:alpha:]]+) (?<message>.+)\Z/.match(str)
arr = [matching["command"], matching["message"]]
matching=/\A\/create(?[[:alpha:]+)(?。+)\Z/.match(str)
arr=[匹配[“命令”],匹配[“消息”]]
下面是正则表达式工作的演示:
更多关于regex的信息可以在Ruby文档中找到:
具体来说,请参见使用可选的第二个参数,
limit
您的演示没有提供OP问题的答案。@LacostnyCoder您是对的,我应该更清楚地说明,此“演示”只显示了适用于给定字符串格式的正则表达式。为什么需要正则表达式?您的规则是什么?我们是否要跳过第一个单词,让第二个单词成为数组的第一个元素,让spring的其余部分成为数组的第二个元素?请回答我的问题。哎呀,我知道我写的是“春天”,意思是“绳子”。我问了一个问题。你看到了我的问题,但没有回答。我要求你回答。你也看到了,但一直保持沉默。我已经给了你一张否决票,以换取你的粗鲁。你也不经常看到drop(1)
的好用例。@tadman那不是真的。有时,当你想在循环时跳过第一个元素,这样你就可以做一个数组时,你可以使用它。each.drop(1)…
@Zach,不是“经常”在旁观者的眼里吗?顺便说一句,deop
是一个可枚举的(),所以在array.each.drop(1)
@ZachTuttle中不需要each
,大多数时候我只是迭代数组的一部分,或者转移不需要的部分。
str = '/create channel welcome message, hello there, any words you like...'
str.split(/\s+/,3).drop(1)
#=> ["channel", "welcome message, hello there, any words you like..."]