[GIS] Inserting space before capital letter in attribute using QGIS field calculator

arcmapattribute-tablefield-calculatorpythonqgis

I have a field, and it has many words in it for every row and I want to insert a space before every capital letter except of the first one.

Example:
I have something like this:

GeorgeJohnMike

or

George smithJohnMike

And I want to modified it some thing like this:

George John Mike

or

George smith John Mike

How can I do it using QGIS or in ArcGis?

Best Answer

FOR QGIS:

You can use below expressions:

replace((regexp_replace("YourField", '(?!^)([A-Z])', ' \\1')),'  ', ' ')

N.B. I am surprised that qgis does not support negative look behind though python 2.7 fully supports it.


FOR ArcGIS:

Basically, this answer is equally applied for ArcGIS and QGIS. I will use regular expression to solve the problem

I would use below function in the arcmap field calculator:

import re
def spacer(text):
    return re.sub(r'([A-Z])',r" \1",text,re.MULTILINE).strip()

or below if there is a single space already before any capital letter in the passed text.

import re
def spacer(text):
    return re.sub(r'([A-Z])',r" \1",text,re.MULTILINE).strip().replace("  "," ")

Example:

demo

Explanation:

I used re.sub(r'([A-Z])',r" \1",text,re.MULTILINE).strip() lets explain it.

re.sub just grabs all that matches ([A-Z]) from the input text and replaces it with the exactly that character but with leading space but it, thus, adds a leading space in the beginning of the line which is unwanted.So I used strip() function to remove unwanted leading and trailing spaces.

Explanation of the regular expression ([A-Z]): It grabs all single character capital letters.

Explanation of the regular expression r \1: Here r is just a formatting flag and in space+\1, \1 is called backreference which returns the character grabbed by the previous regular expression.So replacing text is the exact Capital letters that grabbed by the previous regex plus the leading space.