Yes, there are several ways to make the regex more modular and readable. Here are a few options, ranging from slightly better to significantly better:
1. Named Capture Groups (Best Option - Requires ES2018+ or Babel):
This is the most readable and maintainable approach, but requires a JavaScript environment that supports named capture groups.
const regex = /Assert\.True\((?<actual>.*?),\s*(?<expected>.*?),\s*".*?"\);/;
assertions.forEach(assertion => {
const match = assertion.match(regex);
if (match) {
const actual = match.groups?.actual?.trim();
const expected = match.groups?.expected?.trim();
console.log(`expect.soft(${expected}).toBe(${actual});`);
} else {
console.warn(`Could not parse assertion: ${assertion}`);
}
});
(?<actual>...) and (?<expected>...): These define named capture groups. Instead of referring to the groups by number (e.g., match[1]), you can access them by name using match.groups.actual and match.groups.expected.
match.groups?.actual?.trim(): The optional chaining (?.) is used to safely access the actual property of match.groups in case match.groups is null or undefined. This prevents errors if the regex doesn't match.
2. Using Variables for Parts of the Regex:
This approach breaks down the regex into smaller, more manageable parts.
const assertTrueStart = 'Assert\\.True\\(';
const commaWithWhitespace = ',\s*';
const messagePart = '".*?"\\);';
const regex = new RegExp(
assertTrueStart + '(.*?)' + commaWithWhitespace + '(.*?)' + commaWithWhitespace + messagePart
);
assertions.forEach(assertion => {
const match = assertion.match(regex);
if (match) {
const actual = match[1].trim();
const expected = match[2].trim();
console.log(`expect.soft(${expected}).toBe(${actual});`);
} else {
console.warn(`Could not parse assertion: ${assertion}`);
}
});
assertTrueStart, commaWithWhitespace, messagePart: These variables store the different parts of the regex.
new RegExp(...): The RegExp constructor is used to create the regex from the concatenated strings. This is necessary because the parts are defined as variables.
3. Slightly More Readable Regex (Without Named Groups):
This is a minor improvement over the original, making it a bit easier to understand.