How to replace this form: (word.Word) into (word.\nWord) with regex?

Viewed 43

I want to make a Python code that checks if a string contains something similar to:

  • 'word.Word' => it replaces it with 'word.\nWord'.
  • smallLetter.capitalLetter => smallLeter.\nCapitalLetter.

I found that I should use Python regex (which actually I don't know how to write the format inside it!)

I tried creating this sample:

import re
text = 'What is the.What is thef.How did youDo that?F'
text = re.sub(r"(\.+[A-Z])", r".\n;", text)

Input: 'What are you.How did you.When did youDo that?F'

Output: 'What are you.\now did you.\nhen did youDo that?F'

I think it worked but I don't want the capital letter to be replaced, I want to keep it in the text.

For example: Input: 'Hey.Wow' -> Output: 'Hey.\nWow'

2 Answers

Instead of matching the capital letter, just check that it's there with a positive-lookahead (and same goes for the lower-case letter with a positive-lookbehind):

\.+[A-Z]  -->  (?<=[a-z])\.(?=[A-Z])

Example:

import re

text = 'What is the.What is thef.how did you.Do that?F'
text = re.sub(r"(?<=[a-z])\.(?=[A-Z])", r".\n", text)
print(text)

Will give:

What is the.
What is thef.how did you.
Do that?F

Regex demo

This RE should be good for matching

expr = r"[a-z]\.[A-Z]"

It matches ANY lowercase letter, followed by a dot . and an uppercase letter

You can use the https://regex101.com/ site to check your regexes.

enter image description here

To replace properly across the text, you should use groups:

re_expr = r"([a-z])\.([A-Z])"
teststring = "What is the.What is thef.How did youDo that?F"

re.sub(re_expr, "\\1.\n\\2", teststring)

The updated RE matches the lowercase letter before the . and the uppercase letter after ., and marks them as GROUPS. The group definition "\\1" is later used to insert them at their places in the substituted string.

Related