I had a string like:
x123456@server123:/path/to/somewhere$ ls -ltra
I want to match anything after "$ "
( "$ "
not included. Please, notice the white space.). In this case I would obtein "*ls -ltra*"
.
My code is:
var res = str.match(/\$ (.*)/);
console.log( res[1] );
With that I get the expected string... However, is there another way to get that without capturing groups?
A nodejs try in a 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'
In JavaScript the resulting matching group for any of
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
using
/(?:\$\s*)([^$]+)$/g
would be ls -ltra
https://regex101.com/r/dmVSsL/1 ← I could not explain better
You can also use .split()
var str = "x123456@server123:/path/to/somewhere$ ls -ltra"; var sfx = str.split(/\\$\\s+/)[1]; alert(sfx); // "ls -ltra"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.