barathz
barathz

Reputation: 394

Regular expression to match anything after dollar sign plus white space

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?

Upvotes: 2

Views: 330

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206038

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"

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185025

A 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'

Upvotes: 1

Related Questions