u01jmg3
u01jmg3

Reputation: 730

Notepad++ regex to capitalise the first word of selected sentence

Relates to customising Notepad++. I know TextFX 'Sentence case.' exists but I wanted to control this using my own regex/macro.

Testing against: hello my name is john. hello my name is john. hello my name is john.

Currently I have this which works fine when nothing is selected/highlighted with the mouse.

Find what:    ((?<=^|(?<=[.!?]\s)))(\w)
Replace with: \u$0

However, when I select/highlight the second (middle) sentence only (starting at the h and finishing on the period .), the regex does nothing. Note: I have 'Use selection' ticked in N++ and am using 'Replace All'.

This makes sense because the regex is looking for the start of a line or the char pattern .!? followed by a space.

My question is how to alter the regex so that it works when selecting/highlighting any sentence, no matter if it isn't at the beginning of a line as per my example.

I have tried adding in a negative lookbehind to match when no characters are found but I only managed to uppercase the first word of every sentence.

Upvotes: 4

Views: 730

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

The ^ matches the start of a line, while your selected region is not at the line start. You may replace it with \A, the start of the matching string. Since it will match at each selected region, you cannot use \w, you need to add + after it so as not to turn each subsequent word char to upper case.

Use

(?<=\A|(?<=[.!?]\s))(\w+)

and replace with \u$0.

enter image description here

Alternative way is to use capturing groups (then, you will be able to match cases where the number of whitespaces between !, ? or . and the next word char is more than one):

(\A|[.!?]\s+)(\w+)

to replace with $1\u$2.

Upvotes: 2

Related Questions