[Haskell-beginners] How to remove leading and trailing non-alpha characters, and multiple consecutive spaces?

Michael Peternell michael.peternell at gmx.at
Fri Jun 7 08:24:03 CEST 2013


Hi,

how about

import Data.Char
let input = " 'John   Doe-Smith' $"
unwords.words $ reverse . dropWhile (not.isAlpha) . reverse $ dropWhile (not.isAlpha) input
Result: "John Doe-Smith"

-Michael

Am 07.06.2013 um 00:36 schrieb "Costello, Roger L." <costello at mitre.org>:

> Hi Folks,
> 
> I have a string that contains a person's name. 
> 
> Prior to the person's name there may be some non-alpha characters. 
> 
> After the person's name there may be some non-alpha characters.
> 
> Between the person's first name and last name there should be only one space.
> 
> I want to remove the leading and trailing non-alpha characters and remove the extra spaces.
> 
> Here is an example string:
> 
> s = "     \"    John     Doe    \"    "
> 
> After processing, I should have:
> 
> 	John Doe
> 
> Below is my implementation. Is there is a shorter and more efficient implementation? 
> 
> ----------------------------------
> import Data.Char
> import Data.List
> 
> s = "     \"    John     Doe    \"    "
> 
> -- remove leading non-alpha characters
> 
> t1 = dropWhile (not . isAlpha) s		-- returns "John     Doe    \"    "
> 
> -- break the string up into a list of words, 
> -- delimited by white space
> 
> t2 = words t1				-- returns ["John","Doe","\""]
> 
> -- create a string consisting of the first 
> -- name, space, last name
> 
> t3 = t2!!0 ++ " " ++ t2!!1 		-- returns "John Doe"
> 
> -- Put it all together:
> 
> t4 = ((words . dropWhile (not . isAlpha)) s)!!0 ++ " " ++ ((words . dropWhile (not . isAlpha)) s)!!1
> 
> 
> 
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners




More information about the Beginners mailing list