I’m using Python 3.10 on Windows 10 and trying the search below:
JavaScript
x
3
1
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r'1 2', 'JohnnyB Cool & JoeCool')
2
'JohnnyB Cool & Joe Cool'
3
If I use just “JohnnyB Cool”, the “B” gets a space before it.
JavaScript
1
3
1
re.sub(r'(.*[A-Z]+[a-z]+)([A-Z])', r'1 2', 'JohnnyB Cool')
2
'Johnny B Cool'
3
Why isn’t the “JohnnyB” substituted in the first search? I’ve also tried:
JavaScript
1
3
1
re.sub(r'(.*)([A-Z]+[a-z]+)([A-Z])', r'1 2 3', 'JohnnyB Cool & JoeCool')
2
'JohnnyB Cool & Joe Cool'
3
To be clear, I want the final answer to be, Johnny B Cool & Joe Cool
.
Advertisement
Answer
You may use this python code:
JavaScript
1
5
1
>>> import re
2
>>> s = 'JohnnyB Cool & JoeCool'
3
>>> print (re.sub(r'B[A-Z]', r' g<0>', s))
4
Johnny B Cool & Joe Cool
5
Explanation:
B
matches whereb
doesn’t i.e. adjacent to another word character[A-Z]
matches an uppercase letter