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.
2
Answers
You could use
String.prototype.matchAll()
: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:The following should be self-explanatory. I’ve just added
r?n
to the regex then used thegroups
property of the return value.