rvg
rvg

Reputation: 11

Capturing empty instance in regex

Please pardon if my questions sounds basic. I have a text string with four values:

Field A|Field B|Field C|Field D

While getting an input one or more of these four values can be left blank, e.g:

Field A||Field C|Field D

Or

Field A||Field C||

I need to write a regex that can capture the values appropriately and assign it to specific buckets. Can someone please help?

Upvotes: 0

Views: 29

Answers (1)

Samuel Toh
Samuel Toh

Reputation: 19238

Depending on the language you are using, they can be slightly different.

The implementation below is based on javascript. Essentially the pattern you're after is something like /(.*?)\|(.*?)\|(.*?)\|(.*)/

What this means is that you're capturing . everything and by specifying *? - this means non greedy capture until the first | pipe is seen.

Since we know there will be 4 groups and the last one will not have a | pipe, then by doing (.*) is adequate for the last set as it just means everything else on the string.

Try this:

const regex = /(.*?)\|(.*?)\|(.*?)\|(.*)/gm;
const str = `Field A||Field C|Field D`;
var m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Upvotes: 1

Related Questions