rath
rath

Reputation: 4059

Matching repeating groups of characters

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

For example,

but not

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

Upvotes: 2

Views: 58

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

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; }

Upvotes: 3

Related Questions