正则表达式匹配任何美元符号后加上空格

时间:2016-09-27 21:16:20

标签: javascript regex match

我有一个字符串:

x123456@server123:/path/to/somewhere$ ls -ltra

我希望在"$ "之后匹配任何内容("$ "未包括在内。请注意空格。)在这种情况下,我会obtein "*ls -ltra*"

我的代码是:

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

有了这个,我得到了预期的字符串......但是,有没有其他方法可以在没有捕获组的情况下获得它?

2 个答案:

答案 0 :(得分:1)

在shell中尝试

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

答案 1 :(得分:0)

在JavaScript中,

的任何匹配组
x123456@server123:/path/to/somewhere$ ls -ltra  
x123456@server123:/path/to/some$$wh$re$ ls -ltra
x123456@server123:/path/to/somewhere$     ls -ltra
// and even:
x123456@server123:/path/to/some$$where$ls -ltra
使用

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

将是ls -ltra

https://regex101.com/r/dmVSsL/1 ←我无法解释更好

您也可以使用.split()

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

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

相关问题