skip to Main Content

I’m trying to create a named match regex expression in JavaScript which captures build information from a multiline string. It tests fine in regex101 but fails to match correctly in JavaScript in a single pass of exec.

When I try the the following regex in JavaScript all that is matched is the first match, i.e. . Everything else shows up as undefined.

When I test the following in regex101.com

/(BuildTimestamp:)(?<timestamp>.*)|(VersionCode:)(?<major>.*)|(VersionName:)(?<minor>.*)/gm
BuildTimestamp:30-May-2023 14:25rn
VersionCode:6rn
VersionName:.0.5rn

I get the following matches:

timestamp: 30-May-2023 14:25
major: 6
minor: .0.5

In JavaScript I’m doing the following:

const regex = /(BuildTimestamp:)(?<timestamp>.*)|(VersionCode:)(?<major>.*)|(VersionName:)(?<minor>.*)/gm;

const match = regex.exec(contents);

If I put the exec in a loop I’m able to capture each named match in turn when exec is called. I’m hoping that there is a way to modify the regex query to capture all of them in one go.

The results of the first match are as follows
enter image description here

2

Answers


  1. You could use String.prototype.matchAll():

    const regex = /(BuildTimestamp:)(?<timestamp>.*)|(VersionCode:)(?<major>.*)|(VersionName:)(?<minor>.*)/gm
    
    const result = `BuildTimestamp:30-May-2023 14:25rn
    VersionCode:6rn
    VersionName:.0.5rn`.matchAll(regex);
    
    console.log([...result]);

    Or you could modify the regular expression to match it all in one go. You may wish to adjust the regular expression further if you don’t want to capture the rn sequences:

    const regex = /(BuildTimestamp:)(?<timestamp>.*)(VersionCode:)(?<major>.*)(VersionName:)(?<minor>.*)/s
    
    const result = regex.exec(`BuildTimestamp:30-May-2023 14:25rn
    VersionCode:6rn
    VersionName:.0.5rn`);
    
    console.log(result);
    Login or Signup to reply.
  2. The following should be self-explanatory. I’ve just added r?n to the regex then used the groups property of the return value.

    const contents =
    `BuildTimestamp:30-May-2023 14:25
    VersionCode:6
    VersionName:.0.5`;
    
    const regex = /BuildTimestamp:(?<timestamp>.*)r?nVersionCode:(?<major>.*)r?nVersionName:(?<minor>.*)/;
    
    const match = regex.exec(contents);
    
    //const { timestamp, major, minor } = match.groups;
    
    console.log(match?.groups);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search