I am trying to create a python label expression where only the first word of the address is labeled. Additionally I only want a label to appear if it is a number not a word.

I have used this script but it still labels numbers in other parts of the field. I only want the first number.

def FindLabel ( [ADDR] ):
  import re
  output = re.sub("[^0-9 ]", "", [ADDR])
  return output

I have also tried this script. It labels the first word, but is not specific on character type.

def FindLabel ([ADDR]) :
    if [ADDR]  is not None:
        split_field = ([ADDR]).split(" ")[0]
        return str(split_field)
        return None

Is there a way to combine these scripts to achieve the label I'm trying to generate?

2 Answers 2


You could get fancier with the regex, or take your split approach and test the result before returning it. Something like:

def FindLabel ([ADDR]) :
    if [ADDR] is not None:
        split_field = ([ADDR]).split(" ")[0]
            return str(int(split_field))
        except ValueError:
    return None

That will try to convert the word to an integer. If it works, return it as a string. If it fails, do nothing and return None later on.


If you did want to get fancier with the regular expression you can. When writing regular expressions I'd recommend a tool like https://www.debuggex.com/ to help see what's going on.

Currently your expression is [^0-9 ] which matches anything that's not a number or a space, and replaces it with an empty string. So for example:

  • "42 Wallaby Way, Sydney" gives you "42 "
  • "Apt 56B, Whitehaven Mansions, Sandhurst Sq, London" gives you " 56 "

Regular expressions are pretty powerful (see https://www.regular-expressions.info/ for tutorials and cheat sheets). In your instance, a regular expression matching the first word of a string, if and only if it is a number, looks like:


To break it down:

  • The ^ at the start (outside brackets) means the start of the string
  • \d is any digit - it's the same as [0-9]
  • + is one or more matches
  • The brackets () put what's inside them into a group, so you can get that value back

So, to put it in your Python function:

import re

def find_label(address):
    match = re.match(r'^(\d+) ', address)
    if match:
        return match.group(1)  # the group of digits

And trialling this with the some addresses:

> find_label('42 Wallaby Way, Sydney')
> find_label('Apt 56B, Whitehaven Mansions, Sandhurst Sq, London')
> find_label('221B Baker Street')  # Note the B is part of the first word
> find_label('742 Evergreen Terrace, Springfield')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.