2013-08-02 13 views
2

我一直在搞這個幾個小時,但我似乎無法破解它。我基本上試圖創建一個類似於PHP的回聲(不帶參數)的js Regexp。以下是模式以及我試圖獲得的值。JavaScript正則表達式來模擬回聲陳述

var reg = /echo +[^\s(].+[//"';]/; 

'echo "test";'.match(reg);    //echo "test"; 
'echo test'.match(reg);     //echo test 
'echo "test me out"; dd'.match(reg); //echo "test me out" 
'echo "test me out" dd'.match(reg);  //echo "test me out" 
'echo test;'.match(reg);    //echo test; 
'echo "test "'.match(reg);    //echo "test " 
"echo 'test'".match(reg);    //echo 'test' 


//These should all return null 
'echo (test)'.match(reg); 
'/echo test'.match(reg); 
'"echo test"'.match(reg); 
"'echo test'".match(reg); 

我已經在這裏做了一個例子: http://jsfiddle.net/4HS63/

+3

模擬?相似嗎?正則表達式所做的是*匹配字符串*,沒有別的。你是否要求「*正則表達式匹配echo語句*」? – Bergi

+0

這正是我所追求的。 – gkiely

+0

您的第一個示例有不一致。你給它一個字符串'echo「test」;'並且說它應該返回''test;「'。你的意思是輸入是「echo」測試;「',還是輸出爲」test「? **編輯**沒關係,我看到這只是對右側的評論,沒有什麼重要的。 –

回答

0

此正則表達式匹配兩者你想要什麼捕獲正在搜索的文本:

var reg = /^[\t ]*echo +(?:'([^']*)'|"([^"]*)"|(\w+))/; 

jsFiddle

例如,'echo "test"'.match(reg)將返回["echo "test"", undefined, "test", undefined],並且可以使用theMatch[2]獲取包含test的字符串。

然而,取決於引號的樣式,可以使用第一,第二或第三捕獲。我不知道如何使它們全都使用相同的捕獲,而不使用lookbehind,這是JavaScript不支持的。

+0

謝謝,你是一個學者和紳士。我忘了一個測試,有沒有一種方法可以在echo之前添加製表符或空格? – gkiely

+1

'/ ...('|「|)(。+?)\ 1 /'? – Bergi

+0

@GrantKiely好的;查看更新後的正則表達式,我在'^'後面加了'[\ t] *' ^'means](http://www.regular-expressions.info/anchors.html)這一行的開頭,'[\ t]'表示標籤或空格(使用[字符類](http: //www.regular-expressions.info/charclass.html))和['*'means](http://www.regular-expressions.info/repeat.html)0或更多 –

2

你似乎在尋找

var reg = /^echo +(?:\w+|"[^"]*"|'[^']*');?/; 
^  // anchor for string beginning 
echo  // the literal "echo" 
+  // one or more blanks 
(?:  // a non-capturing group around the alternation 
\w+  // one or more word characters (== [a-zA-Z0-9_]) 
|  // or 
"[^"]*" // a quote followed by non-quotes followed by a quote 
|'[^']*' // the same for apostrophes 
) 
;?  // an optional semicolon 
+0

+1我剛剛做了:http://jsfiddle.net/4HS63/1/你打我:P –

+0

關閉!但它失敗了「回聲'測試'」 – gkiely

+0

@GrantKiely:哎呀,忘了第二個'*' – Bergi

0

你可以嘗試這種模式,允許逃脫,引號裏的語錄:

/^echo (?:"(?:[^"\\]+|\\{2}|\\[\s\S])*"|'(?:[^'\\]+|\\{2}|\\[\s\S])*'|[a-z]\w*)/ 
+0

[這個答案的jsFiddle](http://jsfiddle.net/roryokane/dV4ZD/)。這個答案適用於問題中的所有測試用例。 –