0

Using ArcGIS Desktop 10.7

I want to substring numbers as text out of a string field into a new string field with field calculator so that I can use them for layer symbology. The field contains highway names such as 'I- 280' and 'State Rte 25' and I want only the '280' and '25' for a new field. Is there a Python conditional statement I can use that will substring the number regardless of digit length, placement (end or between text, eg, "State Rte 25 Bus")?

enter image description here

0
1

You can use a regular expression to extract numerical values from a text.

In the field calculator, select the Python parser, and check Show Codeblock.

The regular expression package should be loaded first, so set the pre-logic script to:

import re

and the script itself is:

re.search("\d+", !FULLNAME!).group(0)
  • \d means: match a digit (0–9)
  • + means: match one or more of the previous
  • group(0) returns the first match

There's no error handling, so this may fail if FULLNAME is empty, or does not contain a digit at all.

For more information see the documentation about regular expressions in Python

3
  • Wow, this completely worked! Thanks!
    – kent
    Nov 11 '20 at 4:06
  • @kent Feel free to mark this as answer ;-)
    – Berend
    Nov 11 '20 at 7:53
  • You probably need to think about edge cases where there are two or more numbers seperated by text. Just make visual spot checks of your results where the FULLNAME looks funny or non-standard, to see whether this really is a problem in your dataset.
    – til_b
    Nov 11 '20 at 9:25
0

You could use the isdigit() string method.

''.join((s for s in !FULLNAME! if s.isdigit()))
3
  • I wasn't able to get this string method to work. I tried import isdigit() as the pre-logic script code and copy/pasted the join expression as script for new field and an error is returned.
    – kent
    Nov 11 '20 at 4:11
  • You don't need to import anything. .isdigit() is a method of any string. What was the error? What is your dataset format (shapefile, FGDB feature class)?
    – user2856
    Nov 11 '20 at 4:21
  • Okay I got it to work. Thanks!
    – kent
    Nov 12 '20 at 3:06

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