Removing Non-Alpha Characters from String

Phillip

Member
Hi. Does anyone know an easy way to remove non-alpha characters from a string? The only way that I can think of is to run a string of replace commands, however, this doesn't look clean at all in my code. If there is an easier way I would rather run that. Here is what I am trying to do:

Original String: A-1 Manufacturing & Co.
New String: A1ManufacturingCo

I can list out all the symbols if needed in a replace command if there is an easy way to group them.

Thanks.
 

Cringer

ProgressTalk.com Moderator
Staff member
Here's my idea... it's not pretty...

Code:
def var lv-input as char no-undo. 
def var lv-output as char no-undo. 
def var lv-char as char no-undo. 
def var lv-i as int no-undo. 
def var lv-j as int no-undo.

/*Find the chars we want*/
message asc("a") asc("z") asc("A") asc("Z") asc("0") asc("9") view-as alert-box.

lv-input = "A-1 Manufacturing & Co".

lv-j = length(lv-input). 

do lv-i = 1 to lv-j:
  lv-char = substring(lv-input,lv-i,1).
  case true:
    when asc(lv-char) ge 97 and asc(lv-char) le 122 then 
      lv-output = lv-output + lv-char.
    when asc(lv-char) ge 65 and asc(lv-char) le 90 then 
      lv-output = lv-output + lv-char.
    when asc(lv-char) ge 48 and asc(lv-char) le 57 then 
      lv-output = lv-output + lv-char.
    otherwise 
      next. 
  end case. 
end. 

message lv-Output view-as alert-box.
 

TomBascom

Curmudgeon
The regex kbase only works on Windows -- and as they say, when you solve a problem using regular expressions you now have two problems...

My 4GL soultions:
Code:
define variable s as character no-undo initial "A-1 Manufacturing & Co.".
define variable n as character no-undo format "x(40)".
define variable i as integer  no-undo.

/* straight-forward */

function isAlphaNum returns logical ( input c as character ):
  return (( c ge "a" and c le "z" ) or ( c ge "0" and c le "9" )).
end.

n = "".
do i = 1 to length( s ):
  if isAlphaNum( substring( s, i, 1 )) then n = n + substring( s, i, 1 ).
end.

display n.

pause.

/* or... a bit less obvious */

function xAlphaNum returns character ( input c as character ):
  return ( if (( c ge "a" and c le "z" ) or ( c ge "0" and c le "9" )) then c else "" ).
end.

n = "".
do i = 1 to length( s ):
  n = n + xAlphaNum( substring( s, i, 1 )).
end.

display n.
 

tamhas

ProgressTalk.com Sponsor
Note that the problem "Remove any character which is not alpha" is a somewhat different problem than "Remove any one of the following non-alpha characters that might appear in the string". For the latter, i.e., where you have an identified list of unwanted characters, replace() is fast and simple.
 
Top