Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove leading and trailing white space from a string

Regular Expressions

Remove leading and trailing white space from a string

by  KevinADC  Posted    (Edited  )
----------------------------
[small]ignore this section:
print[/small]
----------------------------


This common task is best done using two regular expressions:

Code:
[b][black]my[/black][/b] [blue]$string[/blue] [black]=[/black] [red]'[/red][purple]  Mary had a little lamb.  [/purple][red]'[/red][black];[/black]
[blue]$string[/blue] [black]=~[/black] [red]s/[/red][purple]^[purple]\s[/purple]+[/purple][red]/[/red][purple][/purple][red]/[/red][black];[/black] [i][gray]#remove leading spaces[/gray][/i]
[blue]$string[/blue] [black]=~[/black] [red]s/[/red][purple][purple]\s[/purple]+$[/purple][red]/[/red][purple][/purple][red]/[/red][black];[/black] [i][gray]#remove trailing spaces[/gray][/i]
[b][black]print[/black][/b] [blue]$string[/blue][black];[/black]

or as a stand alone function:

Code:
[b][black]my[/black][/b] [blue]$string[/blue] [black]=[/black] [red]'[/red][purple]  Mary had a little lamb.  [/purple][red]'[/red][black];[/black]
[blue]$string[/blue] [black]=[/black] [maroon]rem_spaces[/maroon][black]([/black][blue]$string[/blue][black])[/black][black];[/black]
[b][black]print[/black][/b] [blue]$string[/blue][black];[/black]

[b][black]sub[/black][/b] [maroon]rem_spaces[/maroon] [black]{[/black]
   [b][black]my[/black][/b] [blue]$t[/blue] [black]=[/black] [b][black]shift[/black][/b] [black]||[/black] [b][black]return[/black][/b][black]([/black][fuchsia]0[/fuchsia][black])[/black][black];[/black]
   [blue]$t[/blue] [black]=~[/black] [red]s/[/red][purple]^[purple]\s[/purple]+[/purple][red]/[/red][purple][/purple][red]/[/red][black];[/black] [i][gray]#remove leading spaces[/gray][/i]
   [blue]$t[/blue] [black]=~[/black] [red]s/[/red][purple][purple]\s[/purple]+$[/purple][red]/[/red][purple][/purple][red]/[/red][black];[/black] [i][gray]#remove trailing spaces[/gray][/i]
   [b][black]return[/black][/b] [blue]$string[/blue][black];[/black]
[black]}[/black]


You might be tempted to write one regexp:

Code:
[blue]$string[/blue] [black]=~[/black] [red]s/[/red][purple]^[purple]\s[/purple]+([[purple]\s[/purple][purple]\S[/purple]]+)[purple]\s[/purple]+$[/purple][red]/[/red][purple][blue]$1[/blue][/purple][red]/[/red][black];[/black]

or something similar, but this is invariably much slower.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top