簡體   English   中英

重構 2 個正則表達式

[英]Refactoring 2 Regexps

我想拆分字符串

smartcode = '{{question.answer}}'

最終獲得

'answer'

我知道這行得通

smartcode.split(/\{{(.*?)\}}/).last.split(/\.(?=[\w])/).last

但我猜這不是更好的方法......

我建議:

smartcode = '{{question.answer}}'
smartcode.match(/\.(\w+)/)[1]
#=> "answer"

或者當你想確保特定結構用括號括起來並用點分隔兩個單詞時:

smartcode.match(/{{\w+\.(\w+)}}/)[1]
#=> "answer"

如果你想讓你的答案變得復雜,你不應該選擇\w+而是選擇/.*\.(.*?)\}/ (基本上這將匹配 a .和 a }之間的任何內容

前任:

> smartcode = '{{question.complex answer w/ more than 1 kind of symbols such as $}}'
> smartcode.match(/\.(\w+)/)[1]
=> "complex"
> smartcode.match(/.*\.(.*?)\}/)[1]
=> "complex answer w/ more than 1 kind of symbols such as $"

您可以使用

smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]

/{{[^{}]*\.([^{}]*)}}/正則表達式(參見正則表達式演示)匹配

  • {{ - 一個{{文本
  • [^{}]* - 除{}之外的任何零個或多個字符,盡可能多
  • \. - 一個點
  • ([^{}]*) - 第 1 組(此子字符串將與[/regex/, num]構造一起返回):除{}之外的任何零個或多個字符,盡可能多
  • }} - 一個}}文本。

在線查看 Ruby 代碼

smartcode = '{{question.answer}}'
puts smartcode[/{{[^{}]*\.([^{}]*)}}/, 1]
# => answer

如果您需要獲得多個匹配項,請使用.scan

smartcode = '{{question.answer}} and {{question.author}}'
puts smartcode.scan(/{{[^{}]*\.([^{}]*)}}/)
# => ['answer', 'author']

請參閱此 Ruby 代碼演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM