Write a regex that matches with string separated by dash but should be all upper case or lower case

Viewed 34

I am writing a regex that checks for the strings like

ju-NIP-er-us skop-u-LO-rum and ui-LA-ui LO-iu-yu

the set of characters separated by the -

this is what I have got

let str = "ju-NIP-er-us skop-u-LO-rum";
let str2 = "jU-NiP-Er-us skop-u-LO-rum"
console.log(/^\p{L}+(?:[- ']\p{L}+)*$/u.test(str)) // this matches
console.log(/^\p{L}+(?:[- ']\p{L}+)*$/u.test(str2)) // this also matches but this shouldn't match

The problem is set of characters separated by the - should either be all capital or all smaller ,but right now it is matching the mix characters as well ,see the snippet .How to make this regex match only all small or all caps between dashes.

1 Answers

You may use this regex to make sure to match same case substrings between - or space or ' delimiters:

^(?:\p{Lu}+|\p{Ll}+)(?:[- '](?:\p{Lu}+|\p{Ll}+))*$

RegEx Demo

Non-capturing group (?:\p{Lu}+|\p{Ll}+) matches either 1+ of uppercase unicode letters or 1+ of lowercase unicode letters but not a mix of both cases.

Related