我想拆分字串
smartcode = '{{question.answer}}'
最終獲得
'answer'
我知道這行得通
smartcode.split(/\{{(.*?)\}}/).last.split(/\.(?=[\w])/).last
但我猜這不是更好的方法......
uj5u.com熱心網友回復:
我建議:
smartcode = '{{question.answer}}'
smartcode.match(/\.(\w )/)[1]
#=> "answer"
或者當你想確保特定結構用括號括起來并用點分隔兩個單詞時:
smartcode.match(/{{\w \.(\w )}}/)[1]
#=> "answer"
uj5u.com熱心網友回復:
smartcode.scan(/.*\.(.*?)\}/).flatten.first
uj5u.com熱心網友回復:
您可以使用
smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]
正/{{[^{}]*\.([^{}]*)}}/則運算式(參見正則運算式演示)匹配
{{- 一段{{文字[^{}]*- 除了盡可能多的字符之外{的任何零個或多個字符}\.- 一個點([^{}]*)- 第 1 組(此子字串將與構造一起回傳):除and之外的[/regex/, num]任何零個或多個字符,盡可能多{}}}- 一段}}文字。
在線查看Ruby 代碼:
smartcode = '{{question.answer}}'
puts smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]
# => answer
如果您需要獲得多個匹配項,請使用.scan:
smartcode = '{{question.answer}} and {{question.author}}'
puts smartcode.scan(/{{[^{}]*\.([^{}]*)}}/)
# => ['answer', 'author']
請參閱此 Ruby 代碼演示。
uj5u.com熱心網友回復:
對于更短的答案,您可以只使用 ruby?? 中 String 物件中內置的字串匹配:
smartcode = '{{question.answer}}'
smartcode[/\.(\w )/,1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484983.html
