const regex = /\b\d[\d\- ]*[A-Z]?\b/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('\\b\\d[\\d\\- ]*[A-Z]?\\b', 'g')
const str = `Via Treviso Mare 2 => need to detect 2
8C via Sergio Leone => need to detect 8C
Strada Provinciale 22 C => need to detect 22 C
19-20 Frazione Santa Maria => need to detect 19-20
9 - 11 via Giare => need to detect 9 - 11
Via Cesare Taiti 18-B => need to detect 18-B`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let 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}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions