用于匹配一组大括号之间的所有单词的正则表达式 [英] Regex for matching all words between a set of curly braces

查看:43
本文介绍了用于匹配一组大括号之间的所有单词的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我认识的大多数正则表达式专家来说,这是一个简单的问题,但我正在尝试返回句子中某些花括号之间的单词的所有匹配项;但是 Ruby 只返回一个匹配项,我无法弄清楚究竟是为什么.

A simple question for most regex experts I know, but I'm trying to return all matches for the words between some curly braces in a sentence; however Ruby is only returning a single match, and I cannot figure out why exactly.

我正在使用这个例句:

sentence = hello {name} is {thing}

使用此正则表达式尝试返回{name}"和{thing}":

with this regex to try and return both "{name}" and "{thing}":

sentence[/\{(.*?)\}/]

然而,Ruby 只返回{name}".谁能解释为什么这两个词都不匹配?

However, Ruby is only returning "{name}". Can anyone explain why it doesn't match for both words?

推荐答案

你很接近,但使用了错误的方法:

You're close, but using the wrong method:

sentence = "hello {name} is {thing}"

sentence.scan(/\{(.*?)\}/)
# => [["name"], ["thing"]]

这篇关于用于匹配一组大括号之间的所有单词的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆