TheProletariat
TheProletariat

Reputation: 1056

How would I write a regex that matches the values following a string (to the next comma)

I have a csv of key=value pairs. How do I write a regex that matches only the value "1234$32@a" (or any value following the key "password") without using lookbehind?

system=blah, user=stevedave, password=1234$32@a, mylocation=amsterdam

I have tried the following:

[\n\r].*password=\s*([^\n\r]*) didn't match anything (from another SO thread)
\bpassword=\s+(.*)$            just plain ol' wrong.
\bpassword=.+\b,               matches the whole string password=1234$32@a,
(?:password=)(.+,)\2           not sure I understand backreference correctly

It appears my system doesn't support lookbehinds (and they're too expensive anyway), so that's not an option. Is there another way?

Upvotes: 0

Views: 49

Answers (3)

georg
georg

Reputation: 214959

A common pattern in Javascript, with its infamous lack of lookbehinds is

.replace(/.*(stuff you're interested in).*/, "$1")

for example:

str = "system=blah, user=stevedave, password=1234$32@a, mylocation=amsterdam"

pwd = str.replace(/.+?password=(.+?),.+/, "$1")
document.write(pwd)

.exec or .match followed by [1] are fragile because they fail if there's no match. .replace just returns the original string.

Upvotes: 1

Ben Grimm
Ben Grimm

Reputation: 4371

Match anything other than whitespace or , after password=:

var kv = 'system=blah, user=stevedave, password=1234$32@a, mylocation=amsterdam',
    re = /password=([^\s,]+)/,
    match = re.exec(kv);
alert(match[1]);

Demo: https://regex101.com/r/bE4bZ1/1

Strictly speaking, if you want anything up to the next comma, that can be [^,].

Upvotes: 3

David Faber
David Faber

Reputation: 12485

This should do the trick (I don't know which special characters you might allow, so I specified only the ones in your example):

(?:password\s*=\s*)([A-Za-z0-9@$]+)

Please see Regex 101 demo here.

Upvotes: 1

Related Questions