2

私はこれを数時間いじっていますが、クラックできないようです。私は基本的に、php の echo (パラメーターなし) に似た js Regexp を作成しようとしています。これがパターンと、私が取得しようとしている値です。

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/

4

3 に答える 3

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
于 2013-08-02T16:00:02.270 に答える
0

引用符内でエスケープされた引用符を許可するこのパターンを試すことができます。

/^echo (?:"(?:[^"\\]+|\\{2}|\\[\s\S])*"|'(?:[^'\\]+|\\{2}|\\[\s\S])*'|[a-z]\w*)/
于 2013-08-02T16:10:06.717 に答える
0

この正規表現は、必要なものと一致し、検索対象のテキストをキャプチャします

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

jsフィドル

たとえば、'echo "test"'.match(reg)を返し["echo "test"", undefined, "test", undefined]ます。 を使用theMatch[2]して、 を含む文字列を取得できますtest

ただし、引用のスタイルに応じて、1 番目、2 番目、または 3 番目のキャプチャを使用できます。JavaScript がサポートしていないlookbehindを使用せずに、それらすべてに同じキャプチャを使用させる方法がわかりません。

于 2013-08-02T16:03:52.833 に答える