Great! If you'd like to extract each part of speech individually (e.g., split n., adv. into an array like ['n.', 'adv.']), we can enhance the regex and post-process the results accordingly.
✅ Updated Regex Pattern:
const pattern = /^(\w+)\s+(?:$(.*?)$)?\s*([\w\W]*?)\s*$/m;
This is a slightly refined version of the previous pattern, ensuring better handling of optional spaces around the parts of speech.
✅ JavaScript Code with Individual Parts of Speech Extraction:
const input = `
back n., adv.
bad adj.
bag n.
ball n.
banana n.
band n.
bank (money) n.
bath n
`;
const lines = input.trim().split(/\n/);
const pattern = /^(\w+)\s+(?:$(.*?)$)?\s*([\w\W]*?)\s*$/;
for (const line of lines) {
const match = line.match(pattern);
if (match) {
const word = match[1];
const context = match[2] || null;
const posRaw = match[3];
// Extract individual parts of speech:
// Split on comma + optional space, then trim each one
const posList = posRaw
.split(/,\s*/)
.map(pos => pos.trim())
.filter(pos => pos); // remove empty strings
console.log({ word, context, posList });
}
}
📌 Output for Each Line:
For example, for this line:
back n., adv.
You’ll get:
{
word: 'back',
context: null,
posList: ['n.', 'adv.']
}
And for:
bank (money) n.
You’ll get:
{
word: 'bank',
context: 'money',
posList: ['n.']
}
✅ Notes:
- This handles cases where there's only one part of speech (like
n) or multiple separated by commas.
- You can easily adapt it further if some entries have other delimiters or formatting quirks.
Let me know if you want to normalize the parts of speech (e.g., convert n. → 'noun', etc.)!