ekjcfn3902039
ekjcfn3902039

Reputation: 1839

js regex to capture last word before first comma

I have the following string

const str = "bbb=12m3 3be3 34f4, foo=2344 234234 dqda, baz=asdasd asdasd"
const match = str.match(Need the correct regex here);
console.log(match[match.length-1]);

I would like to extract whatever the last 'word' is before the first comma. In the example above it would be 34f4.

I tried /bbb=(.*?),/ which gave me 12m3 3be3 34f4

I tried /bbb=(.+\s(.*)?),/ which gave me dqda

I feel I'm kinda close but can't quite get it.

Edit - I need to specifically look for the string 'bbb' as other strings may be tested that do not have it, or bbb may be in a different order within the string

ex. I may get

const str = "zzz=12m3 3be3 34f4, foo=2344 234234 dqda, baz=asdasd asdasd"

which would return nothing

Or I may get

const str = "foo=2344 234234 dqda, bbb=12m3 3be3 34f4, baz=asdasd asdasd"

where the bbb is in a different location

Upvotes: 1

Views: 463

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use

/bbb=[^,]*\s([^,\s]*)/

See the regex demo

Details

  • bbb= - a bbb= substring
  • [^,]* - 0 or more chars other than , as many as possible
  • \s - a whitespace
  • ([^,\s]*) - Group 1: zero or more chars other than a comma and whitespace

JS demo:

var strs = ['bbb=12m3 3be3 34f4, foo=2344 234234 dqda, baz=asdasd asdasd','zzz=12m3 3be3 34f4, foo=2344 234234 dqda, baz=asdasd asdasd','foo=2344 234234 dqda, bbb=12m3 3be3 34f4, baz=asdasd asdasd'];
var regex = /bbb=[^,]*\s([^,\s]*)/;
for (var i=0; i<strs.length; i++) {
  var m = strs[i].match(regex);
  console.log(strs[i], "=>", ( m ? m[1] : "None!"));
}

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816442

You can call RegExp#exec once to get only the first match:

console.log(/([^\s,]+),/.exec("bbb=12m3 3be3 34f4, foo=2344 234234 dqda, baz=asdasd asdasd"))

The return values is an array. First element is the whole match, second element the first capture group.

Upvotes: 0

Related Questions