Regex for last capital letter in string

Viewed 424

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"

6 Answers

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"

Update

'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

Old answer that only finds last uppercase

What you are looking for is

/[A-Z](?!.*[A-Z].*)/gm

Playground with tests

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

Playground with tests

*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

Make use of lookahead to assert your position right before the final capital letter.

console.log("HelloMyNameIsNick".replace(/(?=[A-Z][^A-Z]*$)/, ' '));

Another option could be to match an uppercase char, and then match any char except an uppercase char till the end of the string.

Replace with a space and the full match.

[A-Z][^A-Z\n]*$

Regex demo

const pattern = /[A-Z][^A-Z\n]*$/;
const str = "HelloMyNameIsNick";
console.log(str.replace(pattern, " $&"));

Related