I have a regular expression implemented in javascript that checks for all capital letters in a string:
.match(/[A-Z]+[^A-Z]*|[^A-Z]+/g)
then adds a space by .join(" ")
–
How can I write a regular expression that finds only the last capital letter instead, then joins a space before that letter? Thanks for your help.
—
Sample Input: "HelloMyNameIsNick"
Ideal Output: "HelloMyNameIs Nick"
To add a space before the last uppercase letter, greedily match all followed by a single uppercase letter:
"ABCabcABC".replace(/(.*)([A-Z])/, "$1 $2")
"ABCabcAB C"
To add a space before the last uppercase letter for each uppercase sequence, match an uppercase letter that is not followed by another uppercase letter:
"ABCabcAB".replaceAll(/([A-Z](?![A-Z]))/g, " $1")
"AB CabcA B"
'HelloMyNameIsNick'.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2')
Test cases:
console.log(`
HelloMyNameIsNick
Hello
Hello
HELLO
HellO
HeLLo
Hello Test
HELLO TEST
hello test
HELLO 1$@(😎-.aa
HELLO 1$@(😎-.Aa
`.replace(/([^ \n])([A-Z][^A-Z]*$)/gm, '$1 $2'))
Check out test cases which are handled properly:
Hello
Hello
Hello Test
What you are looking for is
/[A-Z](?!.*[A-Z].*)/gm
It finds only the last capital letter.
If you want to find last letter in whole text instead on each line you can replace m (multiline) to s (single line):
/[A-Z](?!.*[A-Z].*)/gs
*Note / /s flag may not be supported in all browsers.
(?!ABC) refers to negative lookahead. It checks conditions in expression but not includes them in the final result. More info
Use a non-greedy quantifier:
/[A-Za-z]*?([A-Z])[^A-Z]*/
I suggest you add beginning and end anchors to make sure that you are matching the entire string, otherwise the pattern will segment strings:
/^[A-Za-z]*?([A-Z])[^A-Z]*$/
Try it out here: https://regex101.com/r/h9Acm6/1