2013-01-10 68 views
4

我試圖用正則表達式做if-then-elsif-then-else-then-end 例子:使用正則表達式中的if-ELSIF-ELSE端

s = "foobar123" 
if end of s is 3 
    then return "foo" 
elsif end of s is 2 
    then return "bar" 
else 
    then return "foobar" 
end 

我發現(?(?=condition)(then1|then2|then3)|(else1|else2|else3))http://www.regular-expressions.info/conditional.html,但不知道如何使它在這方面的工作案件。 這裏是我的if-then-else-then-end正則表達式:

/(?=.*[3])(foo)|(bar)/ 
  • 如果字符串以3
  • 結束,然後返回富
  • 否則返回酒吧

我覺得可以寫在別的其他的if-else母相但不能:(

回答

7

你在使用交替的正確軌道,但你不需要lookaheads。

/.*(foo).*3$|.*(bar).*2$|.*(foobar).*/ 

而且你還得回去:

$1$2$3 

我所有的.*因爲我假設你正在使用foobar作爲佔位符。

+0

嗯,有人會解釋downvote?清楚的是,我知道正則表達式不能奇蹟般地生成「返回值」,但如果「返回」文本在匹配範圍內,那麼在許多實現中,可以連接所有捕獲。 –

+0

看起來很對我... –