Using Regular Expressions to change case
/You can change the case of text with Regular Expressions in some applications and programming languages by placing control strings in the replacement expression indicating the type of conversion you want.
NOTE: The following examples were tested in BBEdit which has a great grep search/replace functionality and which uses \
to indicate capture groups rather than $
as is common in other RegEx implementations.
\U
: Start converting all letters to uppercase. Ex:- Source text:
Hello World
- Selection RegEx:
(Hello) World
- Replacement:
\U\1 World
- Final value: HELLO WORLD
- Comments: Notice
\U
starts uppercase conversion and affects all text following it, regardless of the capture group.
- Source text:
\L
: Start converting all letters to lowercase. Ex:- Source text:
Hello World
- Selection RegEx:
Hello World
- Replacement:
\LHello World
- Final value:
hello world
- Comments: With or Without capture groups, the case control string
\L
affects all text that follows it.
- Source text:
\E
: End most recent conversion setting. Only necessary if you're not using additional control strings to change text case, but wish to stop the initial conversion at some point before the end of the replacement string.- Example 1:
- Source text:
hEllo FuNnY WorlD
- Selection RegEx:
([a-zA-Z]*) ([a-zA-Z]*) ([a-zA-Z]*)
- Replacement:
\U\1 \2 \3
- Final value:
HELLO FUNNY WORLD
- Comments: The initial
\U
control string converts all characters that follow uppercase.
- Source text:
- Example 2:
- Source text:
hEllo FuNnY WorlD
- Selection RegEx:
([a-zA-Z]*) ([a-zA-Z]*) ([a-zA-Z]*)
- Replacement:
\U\1 \L\2 \U\3
- Final value:
HELLO funny WORLD
- Comments: We set a conversion control character before each capture group, resetting the conversion that takes place.
- Source text:
- Example 3:
- Source text:
hEllo FuNnY WorlD
- Selection RegEx:
([a-zA-Z]*) ([a-zA-Z]*) ([a-zA-Z]*)
- Replacement:
\U\1\E \2 \3
- Final value:
HELLO FuNnY WorlD
- Comments: A
\E
control string is used after the initial\U\1
(which converts the first capture group to all caps).\E
ends the uppercase conversion, leaving capture groups 2 and 3 unaffected by the initial\U
.
- Source text:
- Example 1:
More complete info at: https://www.regular-expressions.info/replacecase.html