2016-09-27 146 views
2

後什麼我有一個像串:(。不包括"$ "請注意空格)正則表達式匹配美元符號加空格

[email protected]:/path/to/somewhere$ ls -ltra 

我想匹配任何後"$ "。在這種情況下,我會反對"*ls -ltra*"

我的代碼是:

var res = str.match(/\$ (.*)/); 
console.log(res[1]); 

有了,我得到預期的串......然而,有另一種方式來獲得,如果沒有捕獲組?

+2

你有什麼這麼遠嗎?這不是免費的編碼服務 – devnull69

+0

你的問題是什麼? –

+0

那麼,最新的編輯 - *是否有另一種方式來獲取,而不捕捉團體* - 我認爲,這個問題脫離主題。 **沒有**,這是不可能的。 –

回答

1

嘗試在一個殼:

% nodejs 
> var file = '[email protected]:/path/to/somewhere$ ls -ltra' 
undefined 
> file 
'[email protected]:/path/to/somewhere$ ls -ltra' 
> var matches = file.match(/\$\s+(.*)/); 
undefined 
> matches 
[ '$ ls -ltra', 
    'ls -ltra', 
    index: 36, 
    input: '[email protected]:/path/to/somewhere$ ls -ltra' ] 
> matches[1] 
'ls -ltra' 
0

在JavaScript中所得匹配組任何的

[email protected]:/path/to/somewhere$ ls -ltra 
[email protected]:/path/to/some$$wh$re$ ls -ltra 
[email protected]:/path/to/somewhere$  ls -ltra 
// and even: 
[email protected]:/path/to/some$$where$ls -ltra 

使用

/(?:\$\s*)([^$]+)$/g 

ls -ltra

https://regex101.com/r/dmVSsL/1←我無法解釋更好


您還可以使用.split()

var str = "[email protected]:/path/to/somewhere$ ls -ltra"; 
 
var sfx = str.split(/\$\s+/)[1]; 
 

 
alert(sfx);  // "ls -ltra"