Remove Non-numeric Characters

203
3
3 weeks ago
Labels (3)
FlightDeck
New Contributor III

Hey all,

Looking for a simple way to remove any alphabetical characters from a field leaving only 1-9 and "-". Decimals shouldn't be an issue. Preferably python or arcade expression. Unfortunately Through searching I am unable to find a viable route to accomplish this task though the inverse is readily available. Any help is appreciated. 

0 Kudos
3 Replies
RhettZufelt
MVP Frequent Contributor

Depending on the data, one way without using regular expressions. would be to iterate over the string, and if the values match your 'keeplist', then join them to new string, then split that string into the list.

 

instring = 'your99number/textvaluses-4testing'
keeplist = '0123456789.-'
numList = [i for i in (''.join((num if num in keeplist else ' ') for num in instring)).split()]

 

R_

 

CodyPatterson
Occasional Contributor III

Hey @FlightDeck 

If you would like to use regular expression, you can use this:

import re
def remove_alpha(value):
    return re.sub('[^0-9\-]', '', str(value))

While using it in this setup here:

CodyPatterson_0-1715015568124.png

Hope that helps!

Cody

JoshuaBixby
MVP Esteemed Contributor

I am a big fan of regular expressions, which is why I am so disappointed the Python builtin re module has such weak support for Unicode categories.  Fortunately, it is quite common that people will bundle regex · PyPI with their Python deployments, including Esri.

Using regex instead of re allows for people to use Unicode categories to write regular expressions that are much more portable in this global world we live in:

import regex
def remove_alpha(value):
    return regex.sub("[^\p{NUMBER}\p{DASH}]", "", str(value))