-1

I'm parsing some fields out of a string, and I'm having a bit of difficulty getting the extraction correct.

My string can be formatted as such:

const myString = 'field1=field1_value;field2=field2_value'

Or

const myString = 'field1=field1_value'

In this example below, I'm trying to extract field1 and field2 out of the first string.

I've done something like:

const field1 = myString.match(/field1=(.*)(;)?/);
const field2 = myString.match(/field2=(.*)(;)?/);

The problem with this, is that for field1, it will match all the way from the beginning until the end of the string, including all the other fields. If I make the delimiter a mandatory match, then field2 doesn't match anything, as the last field in the string won't have any delimiters. I want this extraction to happen in a way that if a delimiter is present, it should only match up to that and since the last field doesn't have it, or if it is a single field without the delimiter, it should still extract it.

How can I form my regex to do this type of extraction?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
azdiiv
  • 383
  • 5
  • 17

3 Answers3

1

For a simple pattern like this you don't actually need regex. You could just do something like this: myString.split(';').map(field => field.split('=')[1]) to get an array of values.

Tom Nijs
  • 110
  • 7
0

Your first group should be non-greedy, matching as few characters as possible before the next group. The same would work for subsequent fields as long as they end with a semicolon.

const field1 = myString.match(/field1=(.*?)(;)/);
const field2 = myString.match(/field2=(.*)/);

However, if your final field doesn't end in a semicolon, you'd need a different regex for it.

Edit: Disregard this answer. Anubjava gave you a much better solution in the comments:

const field1 = myString.match(/\bfield1=([^;]+)/);
thingEvery
  • 3,368
  • 1
  • 19
  • 25
0

You may try

(\w+)=([^;]+)

See a demo on regex101.com.

Jan
  • 42,290
  • 8
  • 54
  • 79