3

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)
    else:
        return None

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

3

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]
        try:
            return str(int(split_field))
        except ValueError:
            pass
    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.

1

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:

^(\d+)

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')
'42'
> find_label('Apt 56B, Whitehaven Mansions, Sandhurst Sq, London')
None
> find_label('221B Baker Street')  # Note the B is part of the first word
None
> find_label('742 Evergreen Terrace, Springfield')
'742'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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