Q:

Matching repeating groups of characters

I'm trying to match groups of alphanumerics, optionally separated by the dash -.
For example,

ABC
ABC-DEF
123-DEF-ABC

but not

-
-ABC
ABC-

I've managed to do this in the backend (Java) with \w+(\-?\w+)* which works well enough, but it doesn't seem to translate to JS. I've tried many permutations with various flag settings, to no avail.
What am I doing wrong? The unit tests can be found here. Setting the sticky flag seems to pass most tests, except for the ones with a dash at the end.
Thank you

A:

You could use
/^\w+(-\w+)*$/g

with match for start and end of the string, for it.

var strings = ['ABC', 'ABC-DEF', '123-DEF-ABC', '-', '-ABC', 'ABC-'];

strings.forEach(function (a) {
    console.log(a.match(/^\w+(-\w+)*$/g));
    // with g                         ^
});

strings.forEach(function (a) {
    console.log(a.match(/^\w+(-\w+)*$/));
    // without g                      ^
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

